NSDateFormatter returns nil in swift and iOS SDK 8.0

I am reading a tutorial provided by Raywenderlich, Chapter 29 What's new in testing , and run into some strange problem.

Below is the code in the tutorial that converts a string to a date:

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

DateString has the form

 2014-06-21 14:56:00 EST 

However, the date variable is always zero.

NOTE. When playing this code on the playground, it works correctly, as shown in the figure:

enter image description here

I work in iOS SDK 8.0. Is this an SDK bug?


Update

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

+7
ios
source share
2 answers

When you set the dateFormat line, you must also set the locale property to what is compatible with the format provided. Otherwise, the locale will be based on device settings, which may be incompatible.

The date format specified here will work with the "en" locale, but it will not work with many others, such as "eu". Here is 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 North America. In all other places, this is the wrong time zone. If you change the date string to this:

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

It will then be formatted correctly, regardless of what locale value is set.

+11
source share

NSDateFormatter behavior is highly dependent on it locale . By default, it uses the device locale. If you want a consistent result, you must manually specify locale . In most cases, en_US_POSIX is the best.

The document says:

If you are working with fixed format dates, you must first set the locale standard for the date format to something suitable for your fixed format. In most cases, the best choice is en_US_POSIX, a locale specifically designed to produce results in English, regardless of user and system preferences. en_US_POSIX is also time-invariant (if the USA at some point in the future changes the way the dates are formatted, en_US will change to reflect the new behavior, but en_US_POSIX will not), but between platforms (en_US_POSIX works the same on the iPhone OS as it happens on OS X, and, like on other platforms).

Like this:

 let dateString = "2014-06-21 14:56:00 EST" let dateFormatter = NSDateFormatter() dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz" var date: NSDate? = dateFormatter.dateFromString(dateString) 
+5
source share

All Articles