Strict Date Parsing Gotcha (12 Hour Clock Example)

Be careful when parsing dates from strings. According to Technical Q&A QA1480, dates are parsed depending on a user’s
particular setup, e.g. locale viagra pas cher buy cheap viagra online from india. This happens even though the date format is specified strictly.
To ensure reliable parsing for all users, you need to explicitly set a NSDateFormatter’s locale property.

Example follows for a user that has their clock set to 12 hour:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"HH";
// Prints "(null)"
NSLog(@"%@", [dateFormatter dateFromString:@"13"]);    
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
// Prints "1970-01-01 12:00:00 PM +0000" on my device
NSLog(@"%@", [dateFormatter dateFromString:@"13"]);

Leave a Reply

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