Tuesday, February 07, 2012

Easily Localize Custom NSDateFormatter Date Format Strings in iOS 4+

Apple ships a lot of new APIs with every major iOS release. They claimed iOS 4 had over 1,500 new APIs, and the same claim is repeated for iOS 5!
Any way you slice it, a lot of new code
It's easy for a new API that is developerlife altering to slip through a release undetected.

Which is exactly what happened to me for new in iOS 4 API [NSDateFormatter dateFormatFromTemplate:options:locale:]

Why is this API such a big? It gives developers an easy way to generate a custom date or time string for display to the user. Cocoa Touch (and Cocoa before it) have had predefined NSDateFormatterStyle that correlated to specific date or time display representations. For example, NSDateFormatterShortStyle used for dates would be 11/23/37 and for time 3:30pm. But the really big deal was that if you use these predefined styles they would get localized based on the NSLocale of the device. Meaning the short date format in the U.K. would output 23/11/37 and 15:30 respectively.

If you wanted a custom format and localization, like just month and day, you were out of luck without writing it yourself, which means you usually just used the pre-defined styles. Until iOS 4 that is!
Starting in iOS 4, you could not do stuff like this (straight from the documentation):
NSString *formatString = [NSDateFormatter dateFormatFromTemplate:@"EdMMM" options:0
locale:[NSLocale currentLocale]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:formatString];
NSString *todayString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"todayString: %@", todayString);

Which results in this output formatted for the US like this:
2012-02-07 09:32:16.725 Untitled 2[1803:707] todayString: Tue, Feb 7

And when the locale is, for example, Great Britain, the output is this with the same code:
2012-02-07 09:36:32.439 Untitled 2[1839:707] todayString: Tue 7 Feb

Notice this even puts a comma in or not as required by the locale!

BTW, the excellent CodeRunner (available on the Mac App Store) is perfect for quickly running these kinds of code snippets to see the output.