DateFormatter date from string returns nil

[亡魂溺海] 提交于 2019-12-19 00:19:36

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/41206810/dateformatter-date-from-string-returns-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!