【发布时间】:2018-03-22 21:29:08
【问题描述】:
我从头开始创建了一个新的 Single View App 项目,并且只将以下代码添加到 ViewController 的 viewDidLoad 方法中:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/yy"
if let date = dateFormatter.date(from: "11/20") {
print("got the date: \(date)")
} else {
print("failed getting the date")
}
上面的代码可以在世界任何地方除了观察Brasília Summer Time (BRST)的城市。
我测试了here 列出的所有 38 个时区的城市,方法是在设置 > 常规 > 日期和时间中更改设备上的时区。我还确认 BRST 城市在 iOS 11.0 设备上运行良好,但 不是 iOS 11.2.6。
还要注意,即使在 iOS 11.2.6 上,我尝试过的几乎每隔一个月/一年的组合都可以正常工作。 只有“11/20”和“11/26”似乎失败了。
为什么对于在 iOS 11.2.6 上遵守 BRST 的城市,此代码返回 nil?
【问题讨论】:
-
您是否能够通过在
dateFormatter上设置TimeZone而不仅仅是使用设备设置来重现此问题?您在日期和时间设置中选择什么时区? -
你是对的 - 如果我设置
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)它不再为“11/20”返回 nil。 -
@shim 我使用圣保罗作为 UTC−02:00 时区。
-
但是
seconds from GMT: 0和UTC-2 不是同一个时区…… -
@shim,对 - 这就是为什么它在将 dateFormatter 的时区更改为非中断时区时起作用的原因。我只是说如果我将设备上的时区保持为 UTC-02:00 并手动设置 dateFormatter 的时区,这是一个潜在的修复/解决方法。
标签: ios nsdateformatter