gpt4 book ai didi

ios - 来自字符串的 DateFormatter 日期返回 nil

转载 作者:IT王子 更新时间:2023-10-29 05:43:48 24 4
gpt4 key购买 nike

由于某些原因,某些设备无法将字符串转换为日期。

这是我的日期转换代码:

func dateFromString(string: String) -> Date? {
let f = DateFormatter.init()
f.dateFormat = "yyyy-MM-dd HH:mm:ss"
return f.date(from: string)
}

现在,通过我的分析平台,我可以捕捉到返回 nil 的时间。我不知道为什么会这样。我认为它与本地,可能与时区或 12/24h 设置有关,但我不知道是什么问题。

更多详情...

我已经跟踪到以下导致零返回的设置:

timezone - Asia/Muscat

local - en_GB

string - "2016-12-18 08:31:43"

但是当我在 Playground 上运行它时,我得到了一个有效日期:

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"

是什么导致 DateFromatter 返回 nil?

最佳答案

如果要向用户显示日期,不要设置固定日期格式字符串。如果您使用固定格式的日期,请先修复您的语言环境

有关详细信息,请参阅 Technical Q&A QA1480标题为“NSDateFormatter 和 Internet 日期”。以下是相关摘录(格式化我的):

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.

关于ios - 来自字符串的 DateFormatter 日期返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41206810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com