convert eastern time to pacific time in swift

To convert Eastern Time to Pacific Time in Swift, you can create a DateFormatter with the source timezone set to Eastern Time, and then set the destination timezone to Pacific Time. Here's an example:

main.swift
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(identifier: "America/New_York") // set source timezone to Eastern Time
let easternDate = dateFormatter.date(from: "2020-06-15 12:00:00")!

dateFormatter.timeZone = TimeZone(identifier: "America/Los_Angeles") // set destination timezone to Pacific Time
let pacificString = dateFormatter.string(from: easternDate)
print(pacificString) // output: "2020-06-15 09:00:00"
485 chars
9 lines

In this example, we create a DateFormatter with a dateFormat of "yyyy-MM-dd HH:mm:ss", which matches the format of our input date string. We then set the timeZone property of the date formatter to "America/New_York", which is the identifier for the Eastern Time timezone.

We then use the date formatter to convert our input string "2020-06-15 12:00:00" to a Date object, which represents the same moment in time, but in the Eastern Time timezone.

Next, we set the timeZone property of the date formatter to "America/Los_Angeles", which is the identifier for the Pacific Time timezone. We then use the date formatter to convert our Date object back into a string, which represents the same moment in time, but in the Pacific Time timezone.

Finally, we print the resulting string "2020-06-15 09:00:00", which is three hours earlier than the original input time, because Pacific Time is three hours behind Eastern Time.

gistlibby LogSnag