How to create an NSDate object

The easiest way to create an NSDate object is to create “right now” with our convenience method date:

NSDate *myDate = [NSDate date];

But if you want to create a date object with a date such as your birthday it gets a little bit trickier, and – more importantly – much less obvious.

To do this, we need to create an NSDateFormatter, tell the formatter how to expect the date, and then use its convenience method dateFromString to create the date:

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"YYYY-MM-DD";
NSDate *myDate = [formatter dateFromString:@"2012-12-12"];

Notice that I tell the date formatter to expect the date as YYYY-MM-DD. I could also have told it to expect it as YYMMDD and then pass @”12-12-12″ in the dateFromString method.

Whichever way you do it, the date format must match your string, otherwise the method returns null.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.