convert alaska time to gmt in swift

To convert Alaska time to GMT in Swift, you can use the DateFormatter and TimeZone classes. Here's an example function that takes an alaskaTime String and returns the equivalent GMT String:

main.swift
func convertAlaskaTimeToGMT(alaskaTime: String) -> String? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // Change to your input date format
    
    // Set input time zone to Alaska time
    let alaskaTimeZone = TimeZone(identifier: "America/Anchorage")
    dateFormatter.timeZone = alaskaTimeZone
    
    if let date = dateFormatter.date(from: alaskaTime) {
        // Convert time zone to GMT
        dateFormatter.timeZone = TimeZone(identifier: "GMT")
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // Change to your output date format
        return dateFormatter.string(from: date)
    } else {
        return nil
    }
}
689 chars
18 lines

Example usage:

main.swift
let alaskaTime = "2022-01-01 12:00:00"
if let gmtTime = convertAlaskaTimeToGMT(alaskaTime: alaskaTime) {
    print(gmtTime) // Output: "2022-01-01 20:00:00"
} else {
    print("Invalid date format")
}
201 chars
7 lines

Note:

  • Change the input and output date formats as needed.
  • Make sure to specify the correct time zone identifiers for Alaska time and GMT.

gistlibby LogSnag