To convert a date from Australian Eastern Time (AET) to GMT (Greenwich Mean Time) in Swift, you can use the DateFormatter
and TimeZone
classes provided by Foundation.
Here's an example function that takes a Date
object in AET and returns a String
representation of the same time in GMT:
main.swift499 chars14 lines
In this function, we first create an instance of DateFormatter
and set its dateFormat
property to a string that specifies the format of our input date. In this example, we're using the format "yyyy-MM-dd HH:mm:ss".
Next, we set the timeZone
property of the formatter to the AET time zone (identified by the string "Australia/Sydney").
We then use the formatter to convert our input date into a local date string representation.
Next, we set the timeZone
property of the formatter to the GMT time zone.
We use this new time zone setting to create a new Date
instance, gmtDate
, by passing the local date string representation we created earlier into the formatter's date(from:)
method.
Finally, we set the formatter's dateFormat
property to include the string "GMT" and use the string(from:)
method to create a String
representation of the date in GMT time zone.
You can use this function like so:
main.swift157 chars4 lines
Note that you'll need to adjust the timeZone
identifiers in this example if you're using a different AET or GMT time zone, or if you're formatting your input date differently.
gistlibby LogSnag