2017-06-18 108 views
0

我從JSON數據庫中提取日期。日期格式如2017-06-16T13:38:34.601767(ISO8601我認爲)。我正在嘗試使用ISO8601DateFormatter將日期從2017-06-16T13:38:34.601767設置爲2017-06-16。到目前爲止,我甚至無法將拉字符串格式化爲日期。將ISO8601字符串轉換爲重新格式化的日期字符串(Swift)

let pulledDate = self.pulledRequest.date 
var dateFormatter = ISO8601DateFormatter() 
let date = dateFormatter.date(from: pulledDate) 
print(date!) //nil 

我不知道如果我有日期的格式錯誤,它如果我不使用ISO8601DateFormatter按預期不ISO8601或。

1.)它是ISO8601日期嗎?
2.)我是否正確使用ISO8601DateFormatter?

謝謝!

+0

你確定你有你的毫秒塊(0.601767)6位數字? –

+0

不幸的是,是的。那也一直在扔我。我看到有人在某處(我知道,這是有幫助的哈哈)說他們有同樣的事情,它是ISO8601 – froggomad

回答

2

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

輸出是2017-06-16 13:38:34 +0000 - 有沒有辦法截斷+0000使用格式器? – froggomad

+1

使用另一個具有相同選項的格式化程序以及'withSpaceBetweenDateAndTime'選項。 – deadbeef

相關問題