Search code examples
iosswiftxcodedateuikit

How to localize the hours in swift?


This is the API response

{
  "session_start_time": "09:05:00",
  "session_end_time": "15:18:00"
}

These hours are based on UTC +0 time zone and I need to convert them to user timezone and show user.

How can I do that?


Solution

  • After days of searching, I found this answer Link

    And find the write solution with this func:

    private func utcToLocal(dateStr: String) -> String? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm:ss"
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        
        if let date = dateFormatter.date(from: dateStr) {
            dateFormatter.timeZone = TimeZone.autoupdatingCurrent
            dateFormatter.dateFormat = "HH:mm"
            
            let tz = TimeZone.current
            if tz.isDaylightSavingTime(for: Date()) {
                // Summertime
                let calendar = Calendar.current
                if let summerDate = calendar.date(byAdding: .hour, value: 1, to: date) {
                    return dateFormatter.string(from: summerDate)
                }else {
                    return dateFormatter.string(from: date)
                }
            }else {
                return dateFormatter.string(from: date)
            }
        }
        return nil
    }