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.swift466 chars10 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