iOS 日期时区转换不起作用

标签 ios swift timezone

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

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

关于iOS 日期时区转换不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42712778/

相关文章:

ios - 如何在UIView中绘制贝塞尔曲线

ios - 在 UIView 上应用渐变未获得预期结果

ios - XcCode5 : How do relationships work with interface builder?

swift - Swift 4 中更简单的字符串切片

arrays - swift 3 : Find index and remove an item from array inside an array of Structs

swift - 设置 UICollectionView 的 UIEdgeInsets

c++ - 更改系统时区成功一次后不再更改

ios - 如何在swift 3中使用addTarget方法

c - POSIX 方式将用户输入的 utc 偏移量转换为日历时间

timezone - 时区只是一个偏移量还是 "more information"?