Here's a code snippet to convert a date from Central Time (CT) to Greenwich Mean Time (GMT) in Swift:
main.swift495 chars10 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