swifttimezonenstimezone

How to convert time between timezones taking daylightsavings into account?


I have the following function for converting time:

static func convert(date: String) -> String {

        let formatter = DateFormatter()
        formatter.dateFormat = "h:m:s a"
        formatter.timeZone = TimeZone(identifier: "UTC")

        let convertedDate = formatter.date(from: date)
        formatter.timeZone = NSTimeZone.local

        return formatter.string(from: convertedDate!)
    }

Since I'm setting the new time zone based on the device's time zone I taught that daylight savings will be taken into account. But when I passed in 2:00:00 PM it returned 3:0:0 pm instead of 4.

Am I missing something, is there an automatic way to correctly convert time between time zones?


Solution

  • Dealing with daylight saving time only makes sense when the date is known. You don't have a date, just a time. So convertedDate will be January 1, 2001. So whatever the daylight saving rule is for the user's timezone and locale on that date will be used when converting the time.

    If you want the time to be treated as "today" then you can set the date formatter's defaultDate.

    formatter.defaultDate = Date()
    

    If you want some other specific date, create a Date as needed and use that to set the defaultDate.