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 conver
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.