Swift:NSDateFormatter dateFromString在设备上返回nil

编程入门 行业动态 更新时间:2024-10-08 06:25:16
本文介绍了Swift:NSDateFormatter dateFromString在设备上返回nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在Obj-c中找到了可以解决我问题的方法,但是我无法翻译代码,所以我想寻求一种Swift解决方案.

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.

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

I'm parsing some data from a JSON file and I get an issue retrieving the date; 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

就像我在代码注释中写的一样,如果我在iOs Simulator或操场上运行日期,则可以正确获取日期的可选类型,但是如果它在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.

任何人都可以帮忙吗?

推荐答案

对于其他到这里并且不阅读初始帖子评论的人;)

@rintaro指出-我的问题也是什么-使用固定格式的日期时必须添加语言环境:

As @rintaro pointed out - and what was my problem too - you have to add a locale when you use fixed-format dates:

如果您使用固定格式的日期,则应首先设置 日期格式化程序的语言环境应为适合您的固定格式的语言环境 格式.在大多数情况下,最好的语言环境是en_US_POSIX

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

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

因此,在 Swift 3 中,您必须添加

So in Swift 3 you would have to add

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

更多推荐

Swift:NSDateFormatter dateFromString在设备上返回nil

本文发布于:2023-11-26 23:35:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635670.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:设备   NSDateFormatter   Swift   nil   dateFromString

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!