convert pacific time to eastern time in swift

To convert Pacific time to Eastern time in Swift, you can use the NSDateFormatter class to convert a String representation of a date and time from one time zone to another. You'll need to create two NSDateFormatter objects – one for the Pacific time zone and one for the Eastern time zone – and set their time zones accordingly.

Here's an example:

main.swift
let pacificDateString = "2021-02-18 12:00:00" // example date
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(name: "America/Los_Angeles")
let pacificDate = dateFormatter.dateFromString(pacificDateString)!

dateFormatter.timeZone = NSTimeZone(name: "America/New_York") // switch to Eastern time zone
let easternDateString = dateFormatter.stringFromDate(pacificDate)
print(easternDateString)
466 chars
10 lines

In this example, we create a String representation of a date and time in the Pacific time zone (pacificDateString). We then create an NSDateFormatter object and set its dateFormat property to match the format of the input string. We also set its timeZone property to the Pacific time zone.

Next, we use the dateFromString method of the NSDateFormatter object to convert the input string to an NSDate object in the Pacific time zone. We force-unwrap the result with the ! operator because we know the input string is in the correct format.

Finally, we switch the time zone of the NSDateFormatter object to the Eastern time zone and use its stringFromDate method to convert the NSDate object back to a String representation in the Eastern time zone. We print the resulting string to the console.

gistlibby LogSnag