convert pacific time to gmt in swift

Here's an example function in Swift that converts a given date in Pacific time to GMT:

main.swift
func pacificToGMT(date: Date) -> Date? {
    let pacific = TimeZone(identifier: "America/Los_Angeles")
    let gmt = TimeZone(identifier: "GMT")
    
    let formatter = DateFormatter()
    formatter.timeZone = pacific
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    
    if let pacificTime = formatter.date(from: formatter.string(from: date)) {
        let gmtOffset = TimeInterval(gmt!.secondsFromGMT(for: pacificTime))
        let gmtTime = Date(timeInterval: gmtOffset, since: pacificTime)
        return gmtTime
    }
    
    return nil
}
550 chars
17 lines

This code creates two TimeZone objects for Pacific time and GMT, respectively. It then creates a DateFormatter object with the Pacific time zone and a format of "yyyy-MM-dd HH:mm:ss".

The code then converts the input date to Pacific time using the formatter, retrieves the GMT offset for that time, and creates a new Date object with the offset applied.

Note that this function may return nil if the input date is formatted incorrectly or cannot be converted to Pacific time. Additionally, since time zones can be affected by daylight saving time, the conversion between Pacific time and GMT may not always be consistent.

gistlibby LogSnag