Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateFormatter date from string returns nil

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 ?

like image 565
David Ben Ari Avatar asked Dec 18 '16 08:12

David Ben Ari


1 Answers

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 and NSDateFormatter.timeStyle) or generate your date format string from a template (using NSDateFormatter.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.

like image 167
Anton Strogonoff Avatar answered Oct 14 '22 22:10

Anton Strogonoff