Format Dates In Objective-C With NSDate + NSDateFormatter

Matthew Campbell, February 2, 2012

Anyone who uses NSDate knows that the output format can be pretty unpleasant looking. This output is not something that you would generally present to your users. So what is an Objective-C programmer to do with dates?

The answer is to use NSDateFormatter to create date formats and get data objects formatted as strings that you can present to your users.

You will specify date formatter dates using the Unicode data format patterns. So, let’s assume for the moment that you have today’s date set up:

NSDate *todaysDate = [NSDate date];

If you want to present this you would do something like this but with your own UI:

NSDate *todaysDate = [NSDate date];

NSLog(@"Today's date is %@", todaysDate);

The output would look like this if you did it right now with me:

Today's date is 2012-02-02 21:10:57 +0000

That’s not all that pretty is it?

But, let’s bring the date formatter into the picture so you can see how to get some control over this output. We can simple create a new date formatter using NSDateFormatter . Then we can specify any date format that we want.

NSDate *todaysDate = [NSDate date];

NSLog(@"Today's date is %@", todaysDate);
 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.dateFormat = @"EEEE, MMMM d"; 

Now, check out the output:

Today's date (formatted) is Thursday, February 2

Pretty cool right? So, I choose to output the date in a particular way but you can do whatever you want here. See the Unicode date format pattern reference to get more formats that you can use.