且构网

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

NSDateFormatter在swift和iOS SDK 8.0中返回nil

更新时间:2023-11-29 08:13:10

当您设置 dateFormat string您还必须将 locale 属性设置为与提供的格式兼容的属性。否则,区域设置将基于可能不兼容的设备设置。



此处提供的日期格式将与en区域设置一起使用但不起作用与许多其他人,如欧盟。这是一个例子:

  let dateString =2014-06-21 14:56:00 EST

让localeStr =eu//这将给出nil
让localeStr =us//这将成功

let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:localeStr)
dateFormatter.dateFormat =yyyy-MM-dd HH:mm:ss zzz
var date:NSDate? = dateFormatter.dateFromString(dateString)

这里的问题是EST,它只存在于北美洲。在所有其他语言环境中,它是无效的时区。如果您将日期字符串更改为:

 2014-06-21 14:56:00 UTC-5

然后无论什么值 locale $ c $,日期都会正确格式化c>设置为。


I am reading the tutorial provided by Raywenderlich, Chapter 29 What’s New with Testing, and run into a strange problem.

Following is the code in the tutorial converting a string into date:

// Convert date string to date.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz"
var date: NSDate? = dateFormatter.dateFromString(dateString)

The dateString is of the form

2014-06-21 14:56:00 EST

However, the date variable is always nil.

NOTE: when playing this code in the playground, it works properly, as the image shows:

I am working in iOS SDK 8.0. Is it a bug of the SDK?


Updated

I am testing using a latest iPod Touch with iOS 8.

When you set a dateFormat string you must also set the locale property to something that is compatible with the format provided. Otherwise the locale will be based on the device settings which may not be compatible.

The date format you provided here will work with the "en" locale but it will not work with many others, such as "eu". Here's an example:

let dateString = "2014-06-21 14:56:00 EST"

let localeStr = "eu" // this will give nil
let localeStr = "us" // this will succeed

let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: localeStr)
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz"
var date: NSDate? = dateFormatter.dateFromString(dateString)

The problem here is "EST" which only exists in the north america. In all other locales it is an invalid timezone. If you change your date string to this:

"2014-06-21 14:56:00 UTC-5"

Then it the date will correctly format no matter what value locale is set to.