NSDateFormatter fails to return a datetime for UK

2019-05-14 23:52发布

问题:

This question already has an answer here:

  • What is the best way to deal with the NSDateFormatter locale “feechur”? 5 answers

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'.

回答1:

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.