skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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
    }
    

  2. At first create a struct for your response like:

    struct SessionData: Codable {
        
        let sessionStartTime: String
        let sessionEndTime: String
        
        enum CodingKeys: String, CodingKey {
            case sessionStartTime = "session_start_time"
            case sessionEndTime = "session_end_time"
        }
        
    }
    

    Then decode your json to SessionData and go with following lines:

    let dateGetter = NSDateFormatter()
    dateGetter.dateFormat = "HH-mm-ss"
    
    let datePrinter = NSDateFormatter()
    datePrinter.timeZone = NSTimeZone(abbreviation: "GMT") //GMT stands for prefered time zone
    datePrinter.dateFormat = "HH"
    
    let date: NSDate? = dateGetter.dateFromString(yourSessionData.sessionStartTime)
    print(datePrinter.stringFromDate(date!))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search