ISO8601有幾個不同的選項,包括一個時區。看起來默認情況下,ISO8601DateFormatter
需要字符串中的時區指示符。您可以通過使用像這樣的自定義選項禁用此行爲:
let pulledDate = "2017-06-16T13:38:34.601767"
var dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withYear, .withMonth, .withDay, .withTime, .withDashSeparatorInDate, .withColonSeparatorInTime]
let date = dateFormatter.date(from: pulledDate)
如果你想知道什麼是默認選項,只需要運行該代碼在操場:如果
let dateFormatter = ISO8601DateFormatter()
let options = dateFormatter.formatOptions
options.contains(.withYear)
options.contains(.withMonth)
options.contains(.withWeekOfYear)
options.contains(.withDay)
options.contains(.withTime)
options.contains(.withTimeZone)
options.contains(.withSpaceBetweenDateAndTime)
options.contains(.withDashSeparatorInDate)
options.contains(.withColonSeparatorInTime)
options.contains(.withColonSeparatorInTimeZone)
options.contains(.withFullDate)
options.contains(.withFullTime)
options.contains(.withInternetDateTime)
當然,你的字符串不包含時區,日期格式化程序仍將使用其timeZone
屬性在時區中解釋該屬性,根據文檔,該屬性默認爲GMT。
請記住,如果你想詮釋你的約會對象在不同的時區使用格式化之前改變它:
dateFormatter.timeZone = TimeZone(identifier: "Europe/Paris")
你確定你有你的毫秒塊(0.601767)6位數字? –
不幸的是,是的。那也一直在扔我。我看到有人在某處(我知道,這是有幫助的哈哈)說他們有同樣的事情,它是ISO8601 – froggomad