[英]convert ISO8601 String to reformatted date string(Swift)
我正在從JSON數據庫中提取日期。 日期格式為2017-06-16T13:38:34.601767(我認為是ISO8601)。 我正在嘗試使用ISO8601DateFormatter格式化2017-06-16T13:38:34.601767到2017-06-16的日期。 到目前為止,我甚至無法將拉出的字符串格式化為日期。
let pulledDate = self.pulledRequest.date
var dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from: pulledDate)
print(date!) //nil
我不確定我的日期格式是否錯誤,它不是ISO8601,或者我沒有按照預期使用ISO8601DateFormatter。
1.)是ISO8601日期?
2.)我是否正確使用ISO8601DateFormatter?
謝謝!
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
屬性在時區中對其進行timeZone
,根據文檔,該屬性默認為GMT。
如果要在不同的時區解釋日期,請記住在使用格式化程序之前更改它:
dateFormatter.timeZone = TimeZone(identifier: "Europe/Paris")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.