Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateFormatter fails to return a datetime for UK region with 12 hour clock set [duplicate]

This code works for every region/locale combination I can determine EXCEPT if I set my phone to UK region with the 12 hour clock set. Can anyone tell me why?

This works for every region including the UK with 12 hour clock set:

NSDateFormatter *theDateFormatter = [[NSDateFormatter alloc] init];
theDateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ";

NSString *theLastFetchDateString = @"2015-11-13T01:47:52.4630000Z";
NSDate *theLastFetchDate = [theDateFormatter dateFromString:theLastFetchDateString];

This works in every region EXCEPT the UK with the 12 hour clock set:

NSDateFormatter *theDateFormatter = [[NSDateFormatter alloc] init];
theDateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ";

NSString *theLastFetchDateString = @"2015-11-13T18:14:44.1230000Z";
NSDate *theLastFetchDate = [theDateFormatter dateFromString:theLastFetchDateString];

In the second case, theLastFetchDate is always nil.

The main difference I see is the second date is stored in 24 hour format where the parsing device is in 12 hour format, but the formatter HH should be able to handle that, yeah?

The other weird thing, and it is probably just a display thing, is the UK 12 hour clock formats times with 'a.m.' or 'p.m.' where the US 12 hour clock formats them as 'AM' or 'PM'.

like image 220
Rambo Avatar asked Dec 08 '15 18:12

Rambo


1 Answers

You are parsing a RFC 3339/ISO 8601 date. As such, you should set the locale of the formatter to be en_US_POSIX.

theDateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];

See Apple Technical Q&A 1480.

like image 120
Rob Avatar answered Oct 15 '22 13:10

Rob