簡體   English   中英

使用時區轉換字符串時出錯日期

[英]Getting wrong date when converting string with timezone

在Swift游樂場,我運行它。

let string = "2019-01-14T00:00:00+08:00"
let utcTimezone = TimeZone(abbreviation: "UTC")!
let sgtTimezone = TimeZone(abbreviation: "SGT")!

let dfs = DateFormatter()
dfs.timeZone = sgtTimezone
dfs.locale = Locale(identifier: "en_sg")
dfs.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZ"
dfs.calendar = Calendar(identifier: Calendar.Identifier.iso8601)

let date = dfs.date(from: string)!

為什么日期= Jan 13, 2019 at 11:00 PM而不是准確的2019年1月14日凌晨00:00?

嘗試將時區更改為UTC但默認情況下結果是UTC我預計Jan 14, 2019 at 00:00 AM ..或至少1月14日

// This lets us parse a date from the server using the RFC3339 format
let rfc3339DateFormatter = DateFormatter()
rfc3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
rfc3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
rfc3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

// This string is just a human readable format. 
// The timezone at the end of this string does not mean your date 
// will magically contain this timezone. 
// It just tells the parser what timezone to use to convert this 
// string into a date which is basically just seconds since epoch.
let string = "2019-01-14T00:00:00+08:00"

// At this point the date object has no timezone
let shiftDate = rfc3339DateFormatter.date(from: string)!

// If you want to keep printing in SGT, you have to give the formatter an SGT timezone.
let printFormatter = DateFormatter()
printFormatter.dateStyle = .none
printFormatter.timeStyle = .full
printFormatter.timeZone = TimeZone(abbreviation: "SGT")!
let formattedDate = printFormatter.string(from: shiftDate)

你會注意到它打印12am。 您的代碼沒有任何問題。 你只是誤解了Date對象。 大多數人這樣做。

編輯:我用在蘋果的文檔中發現的RFC格式在這里 如果您使用格式化程序,結果是一樣的。 是的,正如rmatty所說,你的格式化程序有一些問題(我已經糾正了:))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM