convert gmt to mountain time in swift

To convert GMT to Mountain Time in Swift, you can use the DateFormatter and TimeZone classes.

Here's an example code snippet that shows how to do it:

main.swift
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(identifier: "GMT") // Set the input timezone to GMT
let date = dateFormatter.date(from: "2022-01-01 12:00:00")!

dateFormatter.timeZone = TimeZone(identifier: "America/Denver") // Set the target timezone to Mountain Time
let mountainTime = dateFormatter.string(from: date)
print(mountainTime) // Output: "2022-01-01 06:00:00"
445 chars
9 lines

In this example, we first create a DateFormatter object and set its dateFormat property to match the format of our input date string ("yyyy-MM-dd HH:mm:ss").

Next, we set the timeZone property of the DateFormatter to the input timezone (GMT) and use it to convert the input date string to a Date object.

Finally, we set the timeZone property to the target timezone (Mountain Time) and use the DateFormatter to convert the date object to a string in the new timezone.

gistlibby LogSnag