Convert from UTC to local timezone give wrong result

烂漫一生 提交于 2020-05-09 11:55:22

问题


Background
I need to convert time string with format: "HH:mm" from UTC to local timezone. For example if UTC time is 09:00, local time (Stockholm/Europe) should be two hours ahead.

Problem
When I convert 09:00 (UTC) to Stockholm/Europe time I get 10:00. It should be 11:00.

func UTCToLocal(date:String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "HH:mm"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

    let dt = dateFormatter.date(from: date)
    dateFormatter.timeZone = TimeZone.current //Stockholm/Europe

    return dateFormatter.string(from: dt!)
}

print(UTCToLocal(date: "09:00")) //prints 10:00

Why is the timezone different from what it suppose to be?


回答1:


You specified only a time, but no day, therefore "09:00" is converted to the date "2000-01-01 09:00:00 +0000". At that moment daylight saving time was not active in Stockholm, and the local time was 10:00.

If you want the conversion for the current day then you can set

dateFormatter.defaultDate = Date()


来源:https://stackoverflow.com/questions/46531583/convert-from-utc-to-local-timezone-give-wrong-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!