Thursday, July 14, 2011

Date Formatter Examples

NSDateFormatter

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: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];
 
 

Format Strings

I want to show an additional example that uses the ICU (International Components for Unicode) library for format strings.

Here is a short list of sample formats using ICU:




The format specifiers are quite straightforward, Y = year, M = month, etc. Changing the number of specifiers for a field, changes the output. For example, MMMM generates the full month name “November”, MMM results in “Nov” and MM outputs “11″.
What follows is an example to create the following date string:

Saturday November 8, 2008:

NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@&quot;EEEE MMMM d, YYYY&quot;];
NSString *dateString = [dateFormat stringFromDate:today];
[dateFormat release];
 
Here’s another example showing the current time:
9:20 AM, PST:

NSDate *today = [NSDate date]; 
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"h:mm a, zzz"];
NSString *dateString = [dateFormat stringFromDate:today];  
[dateFormat release];
 

Date from String

 
While working on an iPhone application recently, I needed to convert a date read from an XML stream that was in the following format: 20081122 to a nicely formatted string for display on the device: Saturday November 22, 2008.


How to get there from here is now obvious, however, when I first encountered this dilemma the solution wasn’t apparent. The reason being, there is significant depth in the Cocoa frameworks and half the battle in becoming proficient as an iPhone developer is to have an opportunity to explore the range of APIs. Albeit the solution was right under my nose the whole time, my first pass was to take a more traditional route of trying to parse the string and rebuild a more “traditional” date format which I could use to create a date object. So, skipping all that, here’s the proper solution…
If you’ve ever worked with dates in Cocoa, chances are you are familiar with the stringFromDate method of the NSDateFormatter. For example, the code below will convert the current date to a string that looks like this: Wednesday November 26, 2008


NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
NSString *dateString = [dateFormat stringFromDate:date];  
[dateFormat release];
 
The trick is two-fold, the date format string to specify desired output, and the method stringFromDate to convert the date object to an NSString.
I’m sure you can see where I’m going with this…the solution I was looking for to convert a date (stored as a string) that was in a pre-defined format (i.e. 20081122) to a date object is as simple as using the method dateFromString. The primary difference is that the format string needs to represent the current format of the date that is to be read (versus the desired output format).
The code below converts a string that represents a date to an NSString object, with the output as follows: Saturday November 22, 2008:

NSString *dateStr = @"20081122";
 
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];  
 
// Convert date object to desired output format
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];  
[dateFormat release];

Setting Locale 

By default, the NSDateFormatter will use the locale set on the device, so no code specific locale changes are required if you want your app to display in the current locale.

However, if you need to display a date in a locale other than the current setting on the device, here’s how to do it:


// Create date object  
NSDate *date = [NSDate date];
 
// Create date formatter
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
 
// Set the locale as needed in the formatter (this example uses Japanese)
[dateFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"]
    autorelease]];
 
// Create date string from formatter, using the current date
NSString *dateString = [dateFormat stringFromDate:date];  
 
// We're done with this now
[dateFormat release];
 
// Show that the locale on the device is still set to US 
NSLocale *locale = [NSLocale currentLocale];
NSLog(@"Current Locale: %@", [locale localeIdentifier]);
 
// Display the date string in format we set above
NSLog(@"Date: %@:", dateString);
 
The output from the code above looks as follows:

 

No comments:

Post a Comment