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):
Q: I'm using NSDateFormatter to parse an Internet-style date, but this fails for some users in some regions. I've set a specific date format string; shouldn't that force NSDateFormatter to work independently of the user's region settings?
A: No. While setting a date format string will appear to work for most users, it's not the right solution to this problem. There are many places where format strings behave in unexpected ways. (…)
If you're working with user-visible dates, you should avoid setting a fixed date format string because it's very hard to predict how your format string will be expressed in all possible user configurations. Rather, you should limit yourself to setting date and time styles (via
NSDateFormatter.dateStyle
andNSDateFormatter.timeStyle
) or generate your date format string from a template (usingNSDateFormatter.setLocalizedDateFormatFromTemplate(String)
).On the other hand, 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", a locale that's specifically designed to yield US English results regardless of both user and system preferences.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With