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

房东的猫 提交于 2019-12-07 14:57:10

问题


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.



来源:https://stackoverflow.com/questions/34163266/nsdateformatter-fails-to-return-a-datetime-for-uk-region-with-12-hour-clock-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!