NSDateFormatter stringFromDate格式化的值有时返回不符合预期的结果

这是一个静态方法,通过把NSDate对象转换成字符串,要求返回的时间格式为yyyy-MM-dd HH:mm:ss

+ (NSString*)stringFromDateSimpleDatetime:(NSDate*)date
{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString* dateString = [dateFormat stringFromDate:date];
    return dateString;
}

通常返回都是正确的,但是有时候发现一部分用户返回的格式不是yyyy-MM-dd HH:mm:ss,例如:

clipboard.png

后来与用户沟通,对方说是因为用了12小时制,但是我不管怎么切换成12小时制,都无法复现这个问题。
请大神帮忙分析,谢谢!困扰了很久了!

阅读 6.3k
2 个回答

参考资料:

https://developer.apple.com/library/ios/qa/qa1480/_index.html

原因:

On iOS, the user can override the default AM/PM versus 24-hour time setting (via Settings > General > Date & Time > 24-Hour Time), which causes NSDateFormatter to rewrite the format string you set, which can cause your time parsing to fail.

看他的意思是说如果用户设置了12/24时制的话,NSDateFormatter会把你的format string改写掉。你这里应该就是HH被改成了a hh

重现条件应该是需要更改手机语言、地区、日历等设置(繁体?改成台湾、香港试试?),然后更改时制,要睡了就不试了。

解决方法:

you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is "en_US_POSIX"

像这样给DateFormatter设置统一的Locale,然后就不管用户怎么改都是按照这个Locale为基准:

    enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];

    [rfc3339DateFormatter setLocale:enUSPOSIXLocale];

链接里有完整的代码。

另:

stackoverflow上还找到相关的问题和一篇博文:
http://stackoverflow.com/questions/143075/nsdateformatter-am-i-doing-s...
http://multinc.com/2009/09/27/iphone-sdk-time-bug-for-international-us...

他们讨论的结果是认为这是个bug,我没仔细看,不过照前面的资料所说应该是Apple的“贴心”设计而不是bug了。题主可以先按前面的试试,不是这个原因的话再去这两个链接看看。

@"yyyy-MM-dd hh:mm:ss"就不会有问题了吧。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题