为什么从字符串创建日期仅在 Real iphone 上失败?

Why create Date from String only failed On Real iphone?

我正在使用以下函数从字符串创建日期。它在模拟器上运行良好。但它在真实 iPhone 上崩溃了。

String: "Tue May 23 23:19:41 +0800 2017"

第一张图是真实调试信息iPhone。第二个是模拟器上的调试信息。

func createDate(fromString string: String) -> Date {
        let formatter = DateFormatter()
        formatter.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
        let date = formatter.date(from: string) //fatal error: unexpectedly found nil while unwrapping an Optional value

        return date!
}

我什至在操场上试过了。真的很奇怪! 谢谢!

这个link可能会解决你的问题.....

Swift

formatter.locale = Locale(identifier: "en_US")

您的日期格式有点错误,请使用下面的示例日期格式。

let dateString : String = "Tue May 23 23:19:41 +0800 2017"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss ZZZ yyyy"
dateFormatter.timeZone = TimeZone(identifier: "GMT")
print(dateFormatter.date(from: dateString))

我敢打赌它会在下一行崩溃,而不是在您评论的那一行崩溃。您正在强制展开结果。如果日期转换失败,强制解包将崩溃并显示您报告的确切错误。

我将 ! 运算符称为 "crash if nil" 运算符。你不应该那样做。你需要防御性编程和return可选,然后编写调用代码来处理转换失败的情况。

其他人已经指出,日期格式化程序取决于设备的区域设置,如果不同,您的转换可能会失败。如果您想为其提供格式不因国家和语言而异的文字字符串,请将格式化程序的语言环境强制为已知语言环境。

来自应用文档

When working with fixed format dates, such as RFC 3339, you set the dateFormat property to specify a format string. For most fixed formats, you should also set the locale property to a POSIX locale ("en_US_POSIX"), and set the timeZone property to UTC.

RFC 3339

In macOS 10.12 and later or iOS 10 and later, use the ISO8601DateFormatter class when working with ISO 8601 date representations.

wiki ISO 8601

为了正确的格式,使用 Date Field Symbol Table