convert gmt to hawaii time in swift

To convert GMT time to Hawaii time in Swift, you need to use the DateFormatter and TimeZone classes. Here's an example code snippet:

main.swift
let gmtDateString = "2021-01-01 10:00:00"
let dateFormatter = DateFormatter()

// Set date format for GMT time
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")

// Parse GMT date string
guard let gmtDate = dateFormatter.date(from: gmtDateString) else {
    return
}

// Set timezone for Hawaii
dateFormatter.timeZone = TimeZone(identifier: "Pacific/Honolulu")

// Format date string for Hawaii time
let hawaiiDateString = dateFormatter.string(from: gmtDate)
print(hawaiiDateString)
537 chars
19 lines

In this example, we first define a string representing the GMT time we want to convert. We then create an instance of DateFormatter and set its date format to match the format of our GMT time string. We also set the time zone of the dateFormatter instance to GMT. Next, we parse the GMT time string into a Date object.

To convert this GMT time to Hawaii time, we set the time zone of the dateFormatter instance to the Pacific/Honolulu time zone (which represents Hawaii time). Finally, we format the date object as a string using the string(from:) method of the dateFormatter instance.

The resulting hawaiiDateString string will represent the same date and time as the original GMT time string, but in Hawaii time.

related categories

gistlibby LogSnag