For some reason some devices fail to convert a string to a date.
This is my date converting code:
func dateFromString(string: String) -> Date? {
let f = DateFormatter.init()
f.dateFormat = "yyyy-MM-dd HH:mm:ss"
return f.date(from: string)
}
Now, through my analytics platform I capture when this return nil. I have no clue why so. I assume it has something to do with local and maybe timezone or 12/24h settings but I can't figure out what is the problem.
More Details...
I have tracked the following settings that causes a nil return:
timezone - Asia/Muscat
local - en_GB
string - "2016-12-18 08:31:43"
But when I run this in playground I get a valid date:
let f = DateFormatter.init()
f.dateFormat = "yyyy-MM-dd HH:mm:ss"
f.locale = Locale.init(identifier: "en_GB")
f.timeZone = TimeZone.init(identifier: "Asia/Muscat")
let s = f.date(from: "2016-12-18 08:31:43")
"Dec 18, 2016, 6:31 AM"
What causes the DateFromatter to return nil ?
If you’re showing your date to the user, don’t set fixed date format string. If you are using fixed-format dates, fix your locale first.
For more details, see Technical Q&A QA1480 titled “NSDateFormatter and Internet Dates”. Below are relevant excerpts (formatting mine):