且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift:NSDateFormatter dateFromString在设备上返回nil

更新时间:2023-11-29 08:21:22

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

@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

https://developer.apple.com/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")