convert gmt to australian western daylight time in swift

To convert a GMT time to Australian Western Daylight Time in Swift, you can use the TimeZone.init(identifier:) initializer to create instances of the two time zones, and then use a DateFormatter to convert a Date object from one time zone to the other. Here's some code that demonstrates this conversion:

main.swift
let gmtDateString = "2021-10-20T12:00:00.000Z"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
dateFormatter.timeZone = TimeZone(identifier: "GMT")
let gmtDate = dateFormatter.date(from: gmtDateString)!

dateFormatter.timeZone = TimeZone(identifier: "Australia/Perth")
let awdtDateString = dateFormatter.string(from: gmtDate)

print("GMT date   : \(gmtDateString)")
print("AWDT date  : \(awdtDateString!)")
452 chars
13 lines

Here, we first create a DateFormatter with the format of the GMT date string and set its time zone to "GMT". We use this formatter to parse the GMT date string and get a Date object in the GMT time zone.

Then, we set the formatter's time zone to "Australia/Perth", which is the time zone identifier for Australian Western Daylight Time. We use this formatter to convert the GMT Date object to a string in the Australian Western Daylight Time zone. Finally, we print out the original GMT date string and the converted AWDT date string for comparison.

Note that the above code assumes that the input GMT date string always has the same format ("yyyy-MM-dd'T'HH:mm:ss.SSSZ") and always ends with the "Z" timezone designator. If your input date strings have a different format or different timezone designators, you'll need to adjust the dateFormat string and/or the TimeZone(identifier:) arguments accordingly.

gistlibby LogSnag