ios - 为什么 Date 在 swift 4 中使用正确的格式时会返回 nil?

标签 ios swift date swift4 date-format

所以这是我要转换的字符串日期

2019-03-22T00:00:00

问题来了 this crash will happen because the date is nil

请记住,我使用了“yyyy-MM-dd'T'HH:mm:ss”或“yyyy-MM-ddTHH:mm:ss”或“yyyy-MM-dd HH:mm:ss”或 yyyy-MM-dd'T'HH:mm:ssZ 和其他一些类似的格式

最佳答案

解析互联网日期时必须设置时区和语言环境:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
// necessary to avoid daylight saving (and other time shift) problems
dateFormatter.timeZone = TimeZone(secondsFromGMT: TimeZone.current.secondsFromGMT())
// necessary to avoid problems with 12h vs 24h time formatting
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
print(dateFormatter.date(from: "2019-03-22T00:00:00"))

默认时区包含有关夏令时的信息,某些特定时间在那里不存在。相反,我们必须使用通用时区。

参见 https://developer.apple.com/library/archive/qa/qa1480/_index.html

2019 年 3 月 22 日午夜左右是伊朗夏令时变化导致一小时不存在的日期和时间。

同样可以使用 ISO8601DateFormatter 来实现:

let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = ISO8601DateFormatter.Options.withInternetDateTime.subtracting(.withTimeZone)
print(dateFormatter.date(from: "2019-03-22T00:00:00"))

关于ios - 为什么 Date 在 swift 4 中使用正确的格式时会返回 nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53933418/

相关文章:

iOS: "Report a Bug"按钮好吗?

ios - 在 iOS 中使用导航的私有(private)属性(property)离线 map

java - DateTimeFormatter 到 DateFormat 的转换

angularjs - orderBy dd/mm/yyyy by year Angular

iphone - 使用UIAppearance分别自定义UIBarButtonItem "Done"样式和 "Plain"样式

ios - (Swift 2) 如何在我的数据库中获取一个随机的 Realm 对象?

ios - Swift fatal error : Index out of range (out of bounds index)

ios - 正在调用我的委托(delegate)函数,但我的 UI 仍然没有相应更新

tsql - T-SQL : Convert varchar date column to date type

ios - Firebase - 读取和获取数据的效率