convert gmt to samoa time in swift

To convert a GMT time to Samoa Time in Swift, you need to create a DateFormatter instance and set its properties to handle the conversion.

Here is an example code snippet to do the conversion:

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

// Create a date object representing the GMT time
let gmtDate = dateFormatter.date(from: "2021-06-25 20:00:00")!

// Set the time zone to Samoa Time (UTC+14)
dateFormatter.timeZone = TimeZone(abbreviation: "SST")

// Format the date string in Samoa Time
let samoaTime = dateFormatter.string(from: gmtDate)

print(samoaTime) // Output: 2021-06-26 10:00:00
496 chars
15 lines

In this example, we first create a DateFormatter and set its dateFormat to match the input date string format ("yyyy-MM-dd HH:mm:ss") that represents the GMT time. We also set the timeZone property of the formatter to the GMT time zone.

Then, we use the date(from:) method of the formatter to create a Date object representing the GMT time.

Next, we change the timeZone of the formatter to Samoa Time (UTC+14).

Finally, we use the string(from:) method of the formatter to create a string representation of the date in Samoa Time, which we output to the console.

Note that Samoa Time is 14 hours ahead of GMT, so the output string shows the time with a 10-hour offset from the input GMT time.

related categories

gistlibby LogSnag