UTC到当地时间 - 错误的结果迅速

问题描述:

我知道有很多线程,但我找不到解决方案,我的问题。也许我看不到解决方案...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时,您的意思是:在MEZ中为12:50给我一个Date对象。

默认情况下,日期显示为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)