convert gmt to alaska time in swift

To convert a GMT date to Alaska Timezone in Swift, you can follow the steps below:

  1. Create an instance of the DateFormatter class:
main.swift
let dateFormatter = DateFormatter()
36 chars
2 lines
  1. Set the timezone of the formatter to GMT:
main.swift
dateFormatter.timeZone = TimeZone(identifier: "GMT")
53 chars
2 lines
  1. Set the date format for parsing the input date (GMT) string:
main.swift
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
49 chars
2 lines
  1. Parse the input GMT date string into a Date object:
main.swift
guard let gmtDate = dateFormatter.date(from: "2021-01-01 12:00:00") else {
    // handle error in parsing the input date string
    return
}
141 chars
5 lines
  1. Set the timezone of the formatter to Alaska Timezone:
main.swift
dateFormatter.timeZone = TimeZone(identifier: "America/Anchorage")
67 chars
2 lines
  1. Finally, format the gmtDate to Alaska Timezone, and get the formatted date string:
main.swift
let alaskaTimeString = dateFormatter.string(from: gmtDate)
59 chars
2 lines

The complete code snippet would look like this:

main.swift
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(identifier: "GMT")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

guard let gmtDate = dateFormatter.date(from: "2021-01-01 12:00:00") else {
    // handle error in parsing the input date string
    return
}

dateFormatter.timeZone = TimeZone(identifier: "America/Anchorage")
let alaskaTimeString = dateFormatter.string(from: gmtDate)

print("GMT time: 2021-01-01 12:00:00")
print("Alaska Time: \(alaskaTimeString)")
489 chars
15 lines

This will print the output as:

main.swift
GMT time: 2021-01-01 12:00:00
Alaska Time: 2021-01-01 03:00:00
63 chars
3 lines

Note: Make sure to replace the input gmtDate string and the Alaska Timezone identifier ("America/Anchorage") with your own values as per your requirement.

gistlibby LogSnag