Date Formatter Examples – Take 2: Format Strings

Mon, Nov 10

In the first post on working with dates several of the examples use the “old style” date format syntax. The examples work, however, 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:

1
2
3
4
5
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
NSString *dateString = [dateFormat stringFromDate:today];
[dateFormat release];

Here’s another example showing the current time:

9:20 AM, PST:

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

More on Date Formatting:

Date Formatter Examples – Take 1: NSDateFormatter
Date Formatter Examples – Take 3: Date from String
Date Formatter Examples – Take 4: Setting Locale

9 comments

That’s exactly what i’m looking for…!

Thank you for your effort!! :)

by Hans on Feb 1, 2010. #

really, thanks alot
that helped me so much

by lastkurutian on Mar 16, 2010. #

Great posting, brief and really informative. Thank you!

by Rex on Apr 13, 2010. #

Great Post. Really Helped me. One question though, instead of CST what if i need -0500. Its just a different representation. I need the hours difference from GMT instead of Time Zone explicitly.

by Sanket Jain on Nov 4, 2010. #

Oh very helpful. That’s just what I was looking for!!!

by Ikus on Nov 19, 2010. #

amazing post .thanks for help

by rick on Jan 24, 2011. #

Great work! Its Very helpful…. Thanks a lot.

by Sandeep Patidar on Apr 16, 2011. #

Thanks for your nice post

by shunmugam on Jul 6, 2011. #

Thanks buddy. . great work

by Kiran on Jul 26, 2011. #