Sinan Noureddine
Sinan Noureddine

Reputation: 506

IOS conversion of UTC to local time not accurate

I'm trying to convert a UTC to device local time in Swift 4. I found many solutions on stackoverflow for that and I implemented them in my code. My code works fine but it doesn't return the right answer.

My code is:

func UTCToLocal() -> String {
    let a = "2:36:27 PM"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "hh:mm:ss aa"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

    let dt = dateFormatter.date(from: a)
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.defaultDate = Date()
    dateFormatter.dateFormat = "hh:mm:ss aa"

    return dateFormatter.string(from: dt!)
}

According to my local time, Lebanon, this method should return the value 5:36:27 PM. However, it is returning 4:36:27 PM.

Note: I checked my device's local time and it's set correctly

Upvotes: 3

Views: 1100

Answers (1)

ielyamani
ielyamani

Reputation: 18581

This is due to Daylight Saving Time in Lebanon. You can take the time offset into consideration by using the daylightSavingTimeOffset(for:) method on your time zone:

func UTCToLocal() -> String {
    let a = "2:36:27 PM"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "hh:mm:ss aa"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    let dt = dateFormatter.date(from: a)

    dateFormatter.timeZone = TimeZone.current
    let offset = dateFormatter.timeZone.daylightSavingTimeOffset(for: dt!)
    dateFormatter.defaultDate = Date()
    dateFormatter.dateFormat = "hh:mm:ss aa"
    return dateFormatter.string(from: dt! + offset)
}

UTCToLocal()

Note that dt is "Jan 1, 2000 at 2:36 PM" since you haven't specified the .day, .month, and .year date components in a

Upvotes: 2

Related Questions