0

I'm getting this UTC time in string format from the server.."2019-12-18T10:58:40Z" Now I want to convert it into local time. For that I referred this link. But it's not working..

What I wanted to achieve was to convert UTC time to local time and set a timer based on that time.

This is what I've tried..

var utcTime = "\(json["expirationDate"]!)"

self.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let date = self.dateFormatter.date(from: utcTime)
let utcDate = date?.toGlobalTime()
let localDate = utcDate?.toLocalTime()

But I'm getting nil values for the dates..

2 Answers2

0

You don't have milliseconds in your UTC date string example. Your date format should be

self.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
Pancho
  • 4,099
  • 1
  • 21
  • 32
  • Thanks @Pancho. Now when I print `localDate`, I get `Optional(2019-12-18 05:48:06 +0000)`. So does this mean the time is 5:48 PM..? –  Dec 18 '19 at 11:16
  • Should mean AM not PM, but you can re-format that again and get whatever date format you need to fit your purpose. This is just the console printing the date object for you. Not sure what date format is used for that. – Pancho Dec 18 '19 at 11:41
0

you have to change this format from "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" to "yyyy-MM-dd'T'HH:mm:ss'Z'"**you have to

let utcTime = "2019-12-18T10:58:40Z"
let dateFormatter = DateFormatter.init()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")!
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
let date = dateFormatter.date(from: utcTime)
print(date)