使用时区转换字符串时得到错误的日期

时间:2019-01-10 05:15:50

标签: swift date

在Swift Playground中,我运行它。

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)!

为什么date = Jan 13, 2019 at 11:00 PM而不是2019年1月14日上午00:00准确?

尝试将时区更改为UTC,但默认情况下结果为UTC 我期望Jan 14, 2019 at 00:00 AM ..或至少是1月14日

1 个答案:

答案 0 :(得分:1)

// 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)

您会注意到它打印上午12点。您的代码没有错。您只是误解了Date对象。大多数人都这样做。

编辑:我使用了Apple文档here中的RFC格式化程序。如果使用格式化程序,结果将相同。是的,正如rmatty所说,格式化程序存在一些问题(我已纠正:))