Search code examples
iosswiftnsdatensdateformatter

Getting incorrect date format after converting


I'm getting this date from API in string format: "2020-01-02T00:00:00".

Now I wanted to convert this date into Date format. So this is what I did for that...

var utcTime = "\(dic["Due_Date"]!)" //Printing `utcTime` gives "2020-01-02T00:00:00"
self.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
self.dateFormatter.locale = Locale(identifier: "en_US")
if let date = dateFormatter.date(from:utcTime) {
  self.scheduledDate = date //HERE I GET THE DATE AS 2020-01-01 18:30:00 UTC
}

The date received in string format is "2020-01-02T00:00:00". But when I convert it to Date format, I get the date as 2020-01-01 18:30:00 UTC which is incorrect.


Solution

  • You have to set Time Zone to UTC (Coordinated Universal Time)

    var utcTime = "2020-01-02T00:00:00" //Printing `utcTime` gives "2020-01-02T00:00:00"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    dateFormatter.locale = Locale(identifier: "en_US")
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    if let date = dateFormatter.date(from:utcTime) {
      print(date)  //HERE I GET THE DATE AS 2020-01-01 18:30:00 UTC
    }
    

    Output :- enter image description here