简体   繁体   English

Swift:NSDateFormatter dateFromString在设备上返回nil

[英]Swift: NSDateFormatter dateFromString returns nil on devices

I found something that could solve my problem in Obj-c, but I'm not able to translate the code, so I'm asking for a Swift solution. 我在Obj-c中找到了可以解决我问题的方法,但是我无法翻译代码,因此我需要一个Swift解决方案。

I'm parsing some data from a JSON file and I get an issue retrieving the date; 我正在从JSON文件中解析一些数据,但在检索日期时遇到问题; here is the code : 这是代码:

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

Like I write in the code comments, I get correctly the optional type of the date if I run it on an iOs Simulator or in the playground, but I get nil if it is running on an iPhone. 就像我在代码注释中编写的一样,如果我在iOs Simulator或操场上运行日期,则可以正确获取日期的可选类型,但是如果它在iPhone上运行,则显示nil。

Can anyone help? 有人可以帮忙吗?

For the others who get here and don't read the comments of the initial post ;) 对于那些到这里并且不阅读初始帖子评论的其他人 ;)

As @rintaro pointed out - and what was my problem too - you have to add a locale when you use fixed-format dates: 正如@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 在大多数情况下,最好的语言环境是en_US_POSIX

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

So in Swift 3 you would have to add 因此,在Swift 3中,您必须添加

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM