Date Formatters Part 1

Sometimes all youre 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:

 // <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.

 // <strong>Output ->  Date: 10/29/2008 08:28pm</strong>  
 NSDate *today = NSDate date;
 NSDateFormatter *dateFormat = NSDateFormatter alloc 
   initWithDateFormat:@"%m/%d/%Y %I:%M%p" allowNaturalLanguage:NO autorelease;
 NSString *dateString = dateFormat stringFromDate:today;
 NSLog@"Date: %@", dateString lowercaseString;

Notice in the above example how I convert the string to lowercase to get pm rather than the default PM. Obviously, if the date contains text (e.g. October) this wouldnt be a good approach.

 //<strong>Output -> Date: Thursday, October 30, 2008</strong>
 NSDate *today = NSDate date;
 NSDateFormatter *dateFormat = NSDateFormatter alloc 
   initWithDateFormat:@"%A, %B %d, %Y" allowNaturalLanguage:NO autorelease;
 NSString *dateString = dateFormat stringFromDate:today;
 NSLog@"Date: %@", dateString;

The above example is similar to the previous, simply using different specifiers to write out the date with full weekday and month.

 // <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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *