convert australian central time to gmt in swift

To convert the Australian Central Time (ACDT/Australian Central Daylight Time or ACST/Australian Central Standard Time) which is a time zone used in South Australia and the Northern Territory to GMT (Greenwich Mean Time), you can use the DateFormatter class in Swift to manipulate the time zone of a Date object.

Here's an example code that converts the current time in ACDT to GMT:

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

let currentLocalTime = Date()
let currentGMTTime = dateFormatter.string(from: currentLocalTime)

dateFormatter.timeZone = TimeZone(identifier: "GMT")
let currentFormattedGMTTime = dateFormatter.date(from: currentGMTTime)

print(currentFormattedGMTTime!) // prints the current time in GMT
442 chars
12 lines

In the example code, we first create an instance of DateFormatter and set its format to "yyyy-MM-dd HH:mm:ss", which is a common date format. We then set the time zone of the DateFormatter instance to ACDT using the time zone identifier "Australia/Adelaide".

Next, we create a Date object to store the current time using the Date() constructor.

We then call dateFormatter.string(from:) with the currentLocalTime object to convert it to a string representation using ACDT time zone.

Further, we reset the time zone of the dateFormatter instance to GMT and call dateFormatter.date(from:) using the previously string-fomatted current time to create a new Date object in the GMT time zone.

Finally, we print the newly created Date object which should be equivalent to the current time in GMT.

gistlibby LogSnag