【问题标题】:how to convert date UTC to local and Local to UTC?如何将日期 UTC 转换为本地和本地到 UTC?
【发布时间】:2017-09-14 10:34:03
【问题描述】:

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

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

2015 年 4 月 1 日下午 5:30 对我来说是本地时间,但我正在反转它

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 本地

【问题讨论】:

  • 当有原生 Swift 替代品时,不要在 Swift 中使用 Foundation 类型。使用TimeZone 而不是NSTimeZone

标签: ios swift3 timezone utc


【解决方案1】:

最后这对我有用

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)

【讨论】:

    【解决方案2】:

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

    来自 Apple 文档

    返回一个对象,将所有消息转发到当前应用程序的默认时区。

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

    【讨论】:

    • 不工作还是一样
    【解决方案3】:

    试试这个:

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

    【讨论】:

    • local time : "Apr 1, 2015, 12:00 PM" UTC time "Apr 1, 2015, 5:30 PM" 它应该被尊重
    • 如果当地时间是下午 12:00,UTC 时间应该是“2015 年 4 月 1 日上午 6:30”
    • @JayprakashSingh 您的设备中设置的时区是什么?
    • 我正在使用模拟器并显示系统时间,即 UTC +5:30
    • @JayprakashSingh Sneha 代码在模拟器中工作我也检查了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 2016-04-07
    相关资源
    最近更新 更多