ios - NSDateFormatter stringFromDate格式化的值有时返回不符合预期的结果
巴扎黑
巴扎黑 2017-04-17 15:14:35
[iOS讨论组]

这是一个静态方法,通过把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,例如:

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

巴扎黑
巴扎黑

全部回复(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"就不会有问题了吧。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号