从UTC转换为本地时区会产生错误的结果 [英] Convert from UTC to local timezone give wrong result
问题描述
背景
我需要将格式为 HH:mm的时间字符串从UTC转换为本地时区。例如,如果UTC时间为09:00,则本地时间(斯德哥尔摩/欧洲)应提前两个小时。
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.
问题
将09:00(UTC)转换为斯德哥尔摩/欧洲时间时,我会得到10:00。应该是11:00。
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?
推荐答案
您仅指定了一个时间,但没有指定日期,因此 09:00将
转换为日期 2000-01-01 09:00:00 +0000。当时斯德哥尔摩的夏令时尚未启用,当地时间为10:00。
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()
这篇关于从UTC转换为本地时区会产生错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!