convert central time to gmt in swift

Here's a code snippet to convert a date from Central Time (CT) to Greenwich Mean Time (GMT) in Swift:

main.swift
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(identifier: "America/Chicago") // set input timezone to CT
let ctDate = dateFormatter.date(from: "2021-10-15 10:30:00")! // example CT date

dateFormatter.timeZone = TimeZone(identifier: "Etc/GMT") // set output timezone to GMT
let gmtDateString = dateFormatter.string(from: ctDate) // convert CT date to GMT date string

print(gmtDateString) // Output: "2021-10-15 15:30:00"
495 chars
10 lines

In the code above, we first create a DateFormatter and set its format to match the input CT date string ("yyyy-MM-dd HH:mm:ss"). We then set the timeZone property of the formatter to "America/Chicago", which is the identifier for CT timezone.

Next, we create a Date object from our input CT date string using the date(from:) method of the formatter. At this point, ctDate is a Date object representing the same moment in time as our input CT date string, but with the time zone set to CT.

We then change the timeZone property of the DateFormatter object to "Etc/GMT", which is the identifier for GMT timezone. Finally, we call the string(from:) method of the formatter to convert ctDate to a string representation that is formatted using GMT time.

Note that in the output string, the time is 5 hours ahead of the input CT time, which is expected since CT is 5 hours behind GMT.

gistlibby LogSnag