Reputation: 23
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.
Upvotes: 1
Views: 106
Reputation: 5225
You also need to set the timezone.
let utcTime = "\(dic["Due_Date"]!)"
let dateFormatter = DateFormatter()
let timezone = TimeZone.init(secondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = timezone!
if let date = dateFormatter.date(from:utcTime) {
print(date) // 2020-01-02 00:00:00 +0000
}
Upvotes: 2
Reputation: 1225
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
}
Upvotes: 3
Reputation: 291
let inputDate = "2020-01-02T00:00:00"
let dateFmt = DateFormatter()
dateFmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
if let date = dateFmt.date(from: inputDate) {
//IF YOU NEED TO CHANGE DATE FORMATE
dateFmt.dateFormat = "dd-MMM-yyyy"
print(dateFmt.string(from: date))
}
Upvotes: 0