swift - UTC 到本地时间 - 错误的结果很快

标签 swift datetime timezone nsdateformatter utc

我知道有很多话题,但我找不到解决我问题的方法。也许我看不到解决方案......

我收到一个 UTC 时间:例如 12:50 我想将这个时间分别转换为 MEZ 到用户设备的时区。对于我的示例,我预计 13:50,因为 atm 是 MEZ +1 到 UTC。

这是我的代码

    //transform date to string
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    let newDateAsString:String = dateFormatter.string(from: self)
    //is 12:50 UTC 

    //transform date to MEZ respectively to the local device timezone
    let dateFormatterToDate = DateFormatter()
    dateFormatterToDate.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    let timeZone = TimeZone.autoupdatingCurrent.identifier as String
    dateFormatter.timeZone = TimeZone(identifier: timeZone)
    //same result with: dateFormatter.timeZone = NSTimeZone.local

    //result is 11:50 but i would expect 13:50
    if let result = dateFormatterToDate.date(from: newDateAsString) {
        return result
    }

结果 11:50 是我当前时区的现在时间。但我不明白这一点。我明确给出了应该转换的日期。有人知道我的错误在哪里吗?

最佳答案

您正在进行的转换与您的意图相反。给出时间为 12:50 的字符串 newDateAsString 没有指定时区,因为您的日期格式字符串不包括时区格式。当您将 dateFormatterToDate 的时区设置为 MEZ,并将 newDateAsString 传递给 dateFormatterToDate 时,您是在说:给我一个日期 对象。

默认情况下,日期显示为 UTC,因此 result 显示为 11:50,因为 MEZ 中的 12:50 是 UTC 中的 11:50。

要将日期格式化为本地时区的字符串,您可以使用如下代码:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = NSTimeZone.local
let localTimeZoneDateString = dateFormatter.string(from: self)

关于swift - UTC 到本地时间 - 错误的结果很快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40842607/

相关文章:

c# - 计算一个月的最后一天

java - java 日历中的 future 日期出现奇怪的行为

c# - ConvertTimeFromUTC,处理澳大利亚 DST

java - 几个 JDK TimeZone 函数的 joda-time 等价物是什么

ios - 在变量中传递类类型

swift - 在 SwiftUI 中连续重复操作

ios - 使用 MIBadgeButton-Swift 向 UIButtonitem 添加角标(Badge)

java - java Date 和 LocalDateTime 中一个月的天数

ios - 单击按钮会隐藏键盘,并且键盘弹起时不会执行操作

postgresql - 微软十六进制日期