NSDateFormatter dateFromString崩溃

时间:2017-02-01 10:22:18

标签: ios nsdateformatter nslocale

Crashlytics服务报告一些崩溃(大约30次崩溃/ 18次用户1000次会议)

这是我的代码:

var brutDate: String = ""
brutDate <- map["send_date"]

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

date = dateFormatter.dateFromString(brutDate)! // here is the crash (this is line 42)

Crashlog是:

Crashed: NSOperationQueue 0x170422a80 :: NSOperation 0x170257190 (QOS: UTILITY)
0  AppName        0x100085f84 specialized SNotification.mapping(Map) -> () (SNotification.swift:42)
1  AppName        0x100084ff4 SNotification.mapping(Map) -> () (SNotification.swift:29)
2  AppName        0x100085a78 protocol witness for Mappable.mapping(Map) -> () in conformance SNotification (SNotification.swift:29)

在这种情况下,brutDate值为2017-01-31 20:02:08

我无法让我的手机崩溃...

编辑:我在法国,应用已部署到加拿大,是否存在Locale问题?

1 个答案:

答案 0 :(得分:4)

可能存在区域设置问题或设备问题。如果设备的24小时时间设置为关闭,则格式化程序将使用该时间,重写您提供的格式字符串。您可以通过将时间格式设置为12小时来在本地重现此内容。

为了防止这种情况,请使用en_US_POSIX语言环境作为日期格式化程序,这将使其使用您提供的格式而不进行修改:

dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")

这解释为here

在任何情况下,如果无法从字符串中恢复,最好不要使用!并记录和错误或提供合理的默认值。