DateFormatter returns unexpected date for Timezone

三世轮回 提交于 2019-11-29 16:25:21

In

let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HHmmss"
timeFormatter.timeZone = TimeZone(identifier: "UTC")
let time = timeFormatter.date(from: "131006")

only a time is provided, but no day/month/year. In this case the date formatter uses a default date of Jan 1, 2001, as you can verify with

print(time!) // 2000-01-01 13:10:06 +0000

Daylight saving time was not active on that day, therefore your local time for that point in time is 14:10, not 15:10.

To solve the issue, you can either combine the date and time strings sent from the server and parse that, or convert the date string first and set it as default date when converting the time string:

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