Date Formatter Examples – Take 1: NSDateFormatter

October 30, 2008

Sometimes all you’re really looking for is a basic chunk of code to get something done. For example, I was working on an application yesterday and needed to display the current date in text format: October 29, 2008. A simple concept for sure, however, with the many nuances of date formatters, it takes some time to pull together the “right” code.

So, to save you some time, here are several simple examples for displaying date information:

1
2
3
4
5
6
 // <strong>Output ->  Date: 10/29/08</strong>
 NSDate *today = [NSDate dateWithTimeIntervalSinceNow:0];
 NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
 [dateFormat setDateStyle:NSDateFormatterShortStyle];
 NSString *dateString = [dateFormat stringFromDate:today];
 NSLog(@"Date: %@", dateString);

Notice above how the style of the output is set using NSDateFormatterShortStyle. There are additional canned formats as well such as NSDateFormatterFullStyle and NSDateFormatterNoStyle.

1
2
3
4
5
6
7
 // <strong>Output ->  Date: 10/29/2008 08:29PM</strong>    
 NSDate *today = [NSDate date];
 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
 [dateFormat setDateFormat:@"MM/dd/yyyy hh:mma"];
 NSString *dateString = [dateFormat stringFromDate:today];
 NSLog(@"date: %@", dateString);
 [dateFormat release];

The example above shows how you can manage memory without using autorelease. As suggested in the comment below (thanks Nick) this is generally a preferred approach on the iPhone where applicable.

These examples merely skim the surface of what you can do when working with dates. Look at the documentation for specifics on how to tweak the specifier strings to create variations of the date output.

More on Date Formatting:

Date Formatter Examples – Take 2: Format Strings
Date Formatter Examples – Take 3: Date from String
Date Formatter Examples – Take 4: Setting Locale

5 comments

Thanks for the post. Just a small point, but you can replace your

NSDate *today = [NSDate dateWithTimeIntervalSinceNow:0];

with a more succinct

NSDate *today = [NSDate date];

I’ve also read that it’s good practice to call release explicitly, rather than relying on autorelease, as there’s an overhead with autoreleasing, and you can’t control when the release will actually occur.

by Nick Ludlam on Oct 30, 2008. Reply #

Good call Nick, I’ve updated the post with a few changes based on your comments.

Thanks.

by John on Oct 30, 2008. Reply #

This examples help a lot… however, is initWithDateFormat:allowNaturalLanguage: method really available fo iphone OS? I saw the documentation and there was no such a method. I think that method is Mac OS only.

by Ignacio on Mar 24, 2009. Reply #

Thanks Ignacio, I have removed the examples that are not applicable for the iPhone.

by John on Mar 24, 2009. Reply #

thanks for giving the simple way solving the example…

by Piyushkumar on Feb 8, 2012. Reply #

Leave a Comment