rilar rilar - 1 year ago 131
Swift Question

Convert from UTC to local timezone give wrong result


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.


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 = 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?

Answer Source

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download