iOS日期时区转换不起作用



在我的操场上,我正在测试日期时间的转换,但似乎没有转换:

import UIKit
let dateString = "2017-12-01 10:00:00 +0000"
print("original date = (dateString)")
var formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
formatter.timeZone = TimeZone(identifier: "Asia/Shanghai")
if let date = formatter.date(from: dateString) {
    print("converted date = (date)")
}
print("test")

输出为:

original date = 2017-12-01 10:00:00 +0000
converted date = 2017-12-01 10:00:00 +0000
test

我期望转换的日期要说类似2017-12-01 18:00:00 +0800(因为上海比UTC 00:00:00提前8小时)

请尝试:

let dateString = "2017-12-01 10:00:00 +0000"
print("original date = (dateString)")
var formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
formatter.timeZone = TimeZone.init(abbreviation: "UTC")
if let date = formatter.date(from: dateString) {
    formatter.timeZone = TimeZone(identifier: "Asia/Shanghai")
    let localTime = formatter.string(from: date)
    print(localTime)
}
print("test")

输出:

original date = 2017-12-01 10:00:00 +0000
2017-12-01 18:00:00 +0800
test

gmt: formatter.timeZone = TimeZone(abbreviation: NSTimeZone.local.abbreviation()!)

UTC: formatter.timeZone = TimeZone(abbreviation: NSTimeZone.default.abbreviation()!)

要显示本地DateTime,我使用GMTTimeZone。

相关内容

  • 没有找到相关文章

最新更新