convert australian central daylight time to gmt in swift

To convert Australian Central Daylight Time (ACDT) to Greenwich Mean Time (GMT) in Swift, you can use the TimeZone and Calendar classes provided by the Foundation framework.

First, you need to create instances of the time zones for ACDT and GMT:

main.swift
let acdtTimeZone = TimeZone(identifier: "Australia/Adelaide")!
let gmtTimeZone = TimeZone(identifier: "GMT")!
110 chars
3 lines

Next, you can create a DateFormatter instance to parse a string representing a date in ACDT:

main.swift
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = acdtTimeZone
123 chars
4 lines

Then, you can use the Calendar class to calculate the equivalent Date object in GMT:

main.swift
let acdtDate = dateFormatter.date(from: "2021-06-01 10:30:00")!
let calendar = Calendar.current
let gmtDate = calendar.date(byAdding: .second, value: -acdtTimeZone.secondsFromGMT(for: acdtDate), to: acdtDate)!
210 chars
4 lines

Finally, you can create another DateFormatter instance to format the gmtDate object as a string:

main.swift
let gmtDateFormatter = DateFormatter()
gmtDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
gmtDateFormatter.timeZone = gmtTimeZone
let gmtDateString = gmtDateFormatter.string(from: gmtDate)
print(gmtDateString) // Output: "2021-06-01 01:00:00"
244 chars
6 lines

In this example, we assume that the input date in ACDT is "2021-06-01 10:30:00". The output date in GMT should be "2021-06-01 01:00:00", because ACDT is nine and a half hours ahead of GMT during daylight saving time.

gistlibby LogSnag