NSDateFormatter在IOS10中返回nil

时间:2016-09-18 14:35:44

标签: ios swift ios10

在iOS 10上运行时,以下代码在XCode 8中崩溃(在以前的iOS版本上没有崩溃):

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SS'Z'"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.locale = NSLocale.currentLocale()


let date = dateFormatter.dateFromString("2016-09-04T08:32:46.195514289Z")!

发生崩溃是因为日期格式化程序返回nil。我尝试播放并更改dateFormat,但结果总是为零。在iOS 10中有什么变化吗?

编辑:当使用Swift 3运行时,相同的代码在Storyboard中工作。似乎问题出现在Swift 2.3和iOS 10上

2 个答案:

答案 0 :(得分:1)

适合我。虽然我使用的是Swift 3:

let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SS'Z'"
df.timeZone = TimeZone(abbreviation: "UTC")
df.locale = NSLocale.current
let date = df.date(from: "2016-09-04T08:32:46.195514289Z")
print("date: \(date)")

打印:

date: Optional(2016-09-04 08:32:46 +0000)

答案 1 :(得分:0)

我在Playground中测试了你的代码(必须将它转换为Swift 3来执行此操作)并且它有效。但是我注意到,在Swift 3中,timeZone被初始化为:

TimeZone(abbreviation: "UTC")

这个初始化程序也可以在NSTimeZone中使用,您可以在Swift 2.x中使用它。根据Apple的文档,当你使用类似" UTC"或" GMT"作为名字。我不确定,我们应该对init(name:)

做些什么