Convert from UTC to local timezone give wrong resu

2020-05-06 08:44发布

问题:

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