DateFormatter returns unexpected date for Timezone

后端 未结 1 963
挽巷
挽巷 2020-12-22 04:30

I\'ve read multiple posts about this, and most were due to not setting a specific Timezone and the system getting the current one. My scenario is slightly different and give

1条回答
  •  醉梦人生
    2020-12-22 04:56

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

    0 讨论(0)
提交回复
热议问题