gpt4 book ai didi

ios - Swift:NSDateFormatter dateFromString 在设备上返回 nil

转载 作者:搜寻专家 更新时间:2023-10-31 08:34:13 24 4
gpt4 key购买 nike

我在 Obj-c 中找到了可以解决我的问题的东西,但我无法翻译代码,所以我要求 Swift 解决方案。

我正在解析 JSON 文件中的一些数据,但在检索日期时遇到问题;这是代码:

println(data) // "Fri, 16 Jan 2015 11:49:00 +0100"

var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE, dd LLL yyyy HH:mm:ss ZZZ"
let formattedDate = dateFormatter.dateFromString(data)

println(formattedDate) // returns 'Optional(2015-01-16 11:49:00 +0100)' if running on an iOs Simulator
// returns 'nil' if runnig on an iPhone

就像我在代码注释中写的那样,如果我在 iOs 模拟器或 Playground 上运行它,我会正确地得到日期的可选类型,但如果它在 iPhone 上运行,我会得到 nil。

有人能帮忙吗?

最佳答案

对于来到这里但没有阅读初始帖子评论的其他人 ;)

正如@rintaro 所指出的——我的问题也是如此——当您使用固定格式的日期时,您必须添加语言环境:

If you're working with fixed-format dates, 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

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW7

所以在 Swift 3 中你必须添加

dateFormatter.locale = Locale(identifier: "en_US_POSIX")

关于ios - Swift:NSDateFormatter dateFromString 在设备上返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28496001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com