convert mountain time to gmt in swift

To convert a Date object from Mountain Time to GMT, we need to follow these steps:

  1. Create a DateFormatter object with the current timezone set to Mountain Time.
  2. Set the timeZone property of the DateFormatter object to GMT.
  3. Use the date(from:) method of the DateFormatter object to convert the original Date object to a new Date object with the timezone set to GMT.

Here's the code:

main.swift
// Get the current date in Mountain Time
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(identifier: "America/Denver")
let mtDateString = dateFormatter.string(from: currentDate)
let mtDate = dateFormatter.date(from: mtDateString)!

// Convert the Mountain Time date to GMT
dateFormatter.timeZone = TimeZone(identifier: "Etc/GMT")
let gmtDateString = dateFormatter.string(from: mtDate)
let gmtDate = dateFormatter.date(from: gmtDateString)!

print("Mountain Time:\t\(mtDateString)")
print("GMT:\t\t\(gmtDateString)")
563 chars
15 lines

In this example, we first get the current date in Mountain Time by creating a DateFormatter object with the timezone set to Mountain Time. We then convert the string representation of the date back to a Date object to ensure that we are working with a valid Date object for the specified timezone.

Next, we create a new DateFormatter object with the timezone set to GMT, and use it to convert the Mountain Time Date object to a string representation of the same date in GMT. Finally, we convert the GMT string representation back to a Date object to ensure that we have a valid Date object for the new timezone.

Note that in this example, we've used "America/Denver" as the identifier for Mountain Time, and "Etc/GMT" as the identifier for GMT. You may need to adjust these identifiers based on your specific timezone requirements.

gistlibby LogSnag