convert australian eastern time to gmt in swift

To convert a date from Australian Eastern Time (AET) to GMT (Greenwich Mean Time) in Swift, you can use the DateFormatter and TimeZone classes provided by Foundation.

Here's an example function that takes a Date object in AET and returns a String representation of the same time in GMT:

main.swift
func convertToGMT(from date: Date) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    formatter.timeZone = TimeZone(identifier: "Australia/Sydney")
    let localDate = formatter.string(from: date)
    
    formatter.timeZone = TimeZone(identifier: "GMT")
    let gmtDate = formatter.date(from: localDate)!
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss 'GMT'"
    let gmtDateString = formatter.string(from: gmtDate)
    
    return gmtDateString
}
499 chars
14 lines

In this function, we first create an instance of DateFormatter and set its dateFormat property to a string that specifies the format of our input date. In this example, we're using the format "yyyy-MM-dd HH:mm:ss".

Next, we set the timeZone property of the formatter to the AET time zone (identified by the string "Australia/Sydney").

We then use the formatter to convert our input date into a local date string representation.

Next, we set the timeZone property of the formatter to the GMT time zone.

We use this new time zone setting to create a new Date instance, gmtDate, by passing the local date string representation we created earlier into the formatter's date(from:) method.

Finally, we set the formatter's dateFormat property to include the string "GMT" and use the string(from:) method to create a String representation of the date in GMT time zone.

You can use this function like so:

main.swift
let inputDate = Date() // current date/time in AET
let outputString = convertToGMT(from: inputDate)
print(outputString) // output: "2021-11-16 07:13:25 GMT"
157 chars
4 lines

Note that you'll need to adjust the timeZone identifiers in this example if you're using a different AET or GMT time zone, or if you're formatting your input date differently.

gistlibby LogSnag