convert australian western time to gmt in swift

To convert Australian Western Time to GMT in Swift, you can use the DateFormatter and TimeZone classes provided by the Foundation framework.

Assuming you have a string representing a date/time in Australian Western Time (AWST), you can use the following code to convert it to a Date object in GMT:

main.swift
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(identifier: "Australia/Perth") // Australian Western Time

if let awstDate = dateFormatter.date(from: "2022-01-01 12:00:00") {
    dateFormatter.timeZone = TimeZone(identifier: "GMT")
    let gmtString = dateFormatter.string(from: awstDate)
    // "2022-01-01 04:00:00"
}
391 chars
10 lines

In this example, the dateFormat property of dateFormatter is set to "yyyy-MM-dd HH:mm:ss" to match the format of the string representing the date/time in Australian Western Time.

The timeZone property of the dateFormatter is set to TimeZone(identifier: "Australia/Perth"), which represents Australian Western Time.

The string representing the date/time in Australian Western Time is passed to dateFormatter.date(from:) to create a Date object in Australian Western Time.

The timeZone property of dateFormatter is then set to TimeZone(identifier: "GMT") to convert the Date object to GMT.

Finally, the string(from:) method of dateFormatter is used to convert the Date object to a string in the format "yyyy-MM-dd HH:mm:ss" representing the same date/time in GMT.

gistlibby LogSnag