convert australian eastern daylight time to gmt in swift

Here's an example code snippet that converts a given Australian Eastern Daylight Time (AEDT) date to GMT using Swift:

main.swift
let dateString = "2021-10-31 09:30:00" // example AEDT date string
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "AEDT")

guard let aedtDate = dateFormatter.date(from: dateString) else {
    fatalError("Invalid AEDT date string: \(dateString)")
}

let calendar = Calendar.current
let gmtTimeZone = TimeZone(abbreviation: "GMT")!
let gmtOffset = gmtTimeZone.secondsFromGMT(for: aedtDate)
let gmtDate = calendar.date(byAdding: .second, value: -gmtOffset, to: aedtDate)!

print("AEDT date: \(aedtDate), GMT date: \(gmtDate)")
610 chars
16 lines

The code creates a date formatter with the AEDT timezone, and uses it to convert the input date string to a Date object. Then, it retrieves the GMT timezone and calculates the offset between the AEDT and GMT timezones for the given AEDT date. Finally, it uses the date(byAdding:to:options:) method of Calendar to subtract the GMT offset from the AEDT date and get the corresponding GMT date. The resulting GMT date can be used for further processing or display.

gistlibby LogSnag