1

I am using this function to convert UTC time to my local time stamp.

    func UTCToLocal(date:String, timeZone: String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "H:mm:ss"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    let dt = dateFormatter.date(from: date)
    dateFormatter.timeZone = TimeZone(identifier: timeZone)
    dateFormatter.dateFormat = "h:mm a"
    return dateFormatter.string(from: time)
}

But this doesn't check DST. So, I am getting one hour difference. Can anyone help me with some general solution for this problem?


Thanks to Leo who have figured out the issue. I have updated the functions as:

    func UTCToLocal(date:String, timeZone: String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
    let dt = dateFormatter.date(from: date)
    dateFormatter.timeZone = TimeZone(identifier: timeZone)
    dateFormatter.dateFormat = "dd-MM-yyyy hh:mm aa"
    return dateFormatter.string(from: dt!)
}

Now the date string in function paramter have value in this format "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'". This solves the issue.

khadeeja
  • 144
  • 2
  • 10
  • Can you show an example of a date and timezone for which you are getting a "one hour difference"? – Sweeper Oct 06 '20 at 07:56
  • The time on iphone is accurate. But my app is displaying wrong time. – khadeeja Oct 06 '20 at 07:59
  • The timezone of your phone is irrelevant. What parameters did you pass to `UTCToLocal`? What did you expect it to return? What did it actually return? – Sweeper Oct 06 '20 at 08:00
  • Okay the values I am passing for function is date = "108:11:00" and timeZone = "America/Toronto". I am getting this timeZone from TimeZone.current.identifier Also the response I am getting is 3:11 AM – khadeeja Oct 06 '20 at 08:08
  • The response I am expecting is 4:11 am. – khadeeja Oct 06 '20 at 08:09

1 Answers1

2

The issue here is the lack of the date. You are always passing only the time components without the day so the daylight savings time Will always be correspondent to January 1st 2001. If you need today’s date you need to set the date formatter defaultDate property to the startOfDay for today. Btw don’t forget to set the locale first to “en_US_POSIX” before setting the fixed date format.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571