Wednesday, November 4, 2009

Date parsing on the iPhone

I recently ran into an unexpected behavior using the NSDateFormatter on the iPhone. I was using it for converting strings to internal NSDate objects. Basically, I was parsing an XML file and was trying to turn the dates into usable dates in my code.

All the examples I had seen for using the NSDateFormatter to convert a string to a date went something like this:

You define the format string of how the date is expected to be parsed via:

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:@"yyyyMMdd hh:mm:ss a"];
[inputFormatter setPMSymbol:@"pm"];
[inputFormatter setAMSymbol:@"am"];

And then you can parse a date using this formatter like so:

NSDate *formatterDate = [inputFormatter dateFromString:@"19990711 10:30:00 pm"];
NSLog(@"date:%@", formatterDate);

Well, this doesn't work quite as you might expect. I discovered that on some iPhones, the end resulting date had a time of 10:30AM rather than PM!

It turns out the difference in behavior was due to the "locale" settings on different phones. Specifically in this case, if the user had their phone configured (via Settings) to use a 24 hour clock display, then my format string specifying the am/pm designation was being completely ignored! All times I was trying to convert from text strings were always ending up as AM times.

To prevent this, I needed to add one more step to my NSDateFormatter configuration after it was initialized:

[inputFormatter setLocale:[NSLocale systemLocale]];

By setting the locale to systemLocale, this would prevent the NSDateFormatter from using any custom locale changes the iPhone user may have made.

No comments:


All content copyright © 2009  Brian Stormont, unless otherwise noted.   All rights reserved.