1

I am trying to convert date time taken from server to local time. I am using DateFormatter(), and after research in the web, the format server is sending looks like: "yyyy-MM-dd'T'HH:mm:ss". However, the actual string server is sending looks like: 2021-06-21T06:00:19.251588, where I guess seconds are given in detailed format. However, when I run it through the function to convert into local time, it return nil. Here is my code:

func utcToLocal(dateStr: String) -> String? {
    //dateStr is 2021-06-21T06:00:19.251588
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    
    if let date = dateFormatter.date(from: dateStr) {
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.dateFormat = "yy.MM.dd"
    
        return dateFormatter.string(from: date)
    }
    return nil
}

Is there any chance I am using wrong dateFormat?

0 Answers0