Swift 3.0 : Convert server UTC time to local time and vice-versa

I don’t know what’s wrong with your code.
But looks too much unnecessary things are there like you’re setting calendar, fetching some elements from string.
Here is my small version of UTCToLocal and localToUTC function.
But for that you need to pass string in specific format. Cause I’ve forcly unwrapped date objects. But you can use some guard conditions to prevent crashing your app.

func localToUTC(dateStr: String) -> String? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "h:mm a"
    dateFormatter.calendar = Calendar.current
    dateFormatter.timeZone = TimeZone.current
    
    if let date = dateFormatter.date(from: dateStr) {
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        dateFormatter.dateFormat = "H:mm:ss"
    
        return dateFormatter.string(from: date)
    }
    return nil
}

func utcToLocal(dateStr: String) -> String? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "H:mm:ss"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    
    if let date = dateFormatter.date(from: dateStr) {
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.dateFormat = "h:mm a"
    
        return dateFormatter.string(from: date)
    }
    return nil
}

and call these function like below.

print(utcToLocal(dateStr: "13:07:00"))
print(localToUTC(dateStr: "06:40 PM"))

Leave a Comment