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: