iOS日期时区转换无效

时间:2017-03-10 07:35:34

标签: ios swift timezone

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

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小时)

2 个答案:

答案 0 :(得分:4)

请试试这个:

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

答案 1 :(得分:0)

GMT: putStrLn

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

要显示本地日期时间,请使用GMTTimeZone。