如何将日期 UTC 转换为本地和本地转换为 UTC?

how to convert date UTC to local and Local to UTC?

我想将日期从本地转换为 UTC,再将 UTC 转换为本地。

例如。 2015 年 4 月 1 日,12:00 下午是 UTC 然后

2015 年 4 月 1 日,5:30 PM 对我来说是本地的,但我正在反转它

let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"[![enter image description here][1]][1]
dateFormatter2.timeZone = NSTimeZone.local
let date2 = dateFormatter2.date(from: "2015-04-01T12:00:00")


dateFormatter2.timeZone = NSTimeZone(name: "UTC")! as TimeZone
let date3 = dateFormatter2.date(from: "2015-04-01T12:00:00")

我收到 2015 年 4 月 1 日 5:30 下午作为 UTC 和 2015 年 4 月 1 日,12:00 本地下午

本地时区始终基于为您的应用设置的默认时区。

来自 Apple 文档

Returns an object that forwards all messages to the default time zone for the current application.

请尝试使用 NSTimeZone.system。这将始终确保它将提供用户在 iOS 设置中设置的时区。

试试这个:

let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter2.timeZone = NSTimeZone.local
dateFormatter2.locale = Locale(identifier: "en_US_POSIX")
let date2 = dateFormatter2.date(from: "2015-04-01T12:00:00")


dateFormatter2.timeZone = TimeZone(identifier: "UTC")
let date3 = dateFormatter2.date(from: "2015-04-01T12:00:00")

终于对我有用了

let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormatter.timeZone = NSTimeZone(name: "UTC")! as TimeZone
        let date = dateFormatter.date(from: "2015-04-01 12:00:00")
        print("UTC time",date!)

        dateFormatter.timeZone = NSTimeZone.local
        let timeStamp = dateFormatter.string(from: date!)

        print("Local time",timeStamp)