convert gmt to pacific time in swift

To convert a Date from GMT to Pacific Time in Swift, you can use the TimeZone class and its init(identifier:) method to create the two time zone objects. Then use these to create the dateFormatter object to format the dates.

main.swift
let gmt = TimeZone(identifier: "GMT")!
let pacificTime = TimeZone(identifier: "America/Los_Angeles")! // or "US/Pacific"
let date = Date()

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = gmt

let gmtDateString = dateFormatter.string(from: date)
print("GMT: ", gmtDateString)

dateFormatter.timeZone = pacificTime

let pacificTimeString = dateFormatter.string(from: date)
print("Pacific Time: ", pacificTimeString)
477 chars
16 lines

In the code above, we:

  1. Create two TimeZone objects, one for GMT and one for Pacific Time.
  2. Create a Date object for the current date and time.
  3. Create a DateFormatter object with a format string that we can use to create a string representation of the dates.
  4. Set the timeZone property of the dateFormatter to the GMT time zone and generate a string representation of the date in GMT.
  5. Set the timeZone property of the dateFormatter to the Pacific Time time zone and generate a string representation of the date in Pacific Time.

You can modify the dateFormat and timeZone properties of the DateFormatter object to fit your needs.

gistlibby LogSnag