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.





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.