convert gmt to australian western time in swift

To convert a date from GMT to Australian Western Time in Swift, you need to use the TimeZone and DateFormatter classes. Here's how you can do it:

main.swift
// create a date formatter for input and output
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

// set the input date to GMT
formatter.timeZone = TimeZone(identifier: "GMT")
let inputDate = formatter.date(from: "2022-01-01 12:00:00")!

// set the output date to Australian Western Time
formatter.timeZone = TimeZone(identifier: "Australia/Perth")

// format the date
let outputDate = formatter.string(from: inputDate)

print(outputDate) // Output: "2022-01-01 20:00:00"
500 chars
16 lines

In this example, we first create a DateFormatter object and set its format to match our input string. We then set the time zone of the formatter to GMT and convert our input string to a date object.

Next, we set the time zone of the formatter to Australian Western Time ("Australia/Perth") and use it to format our date object. Finally, we print the output string to verify the conversion.

gistlibby LogSnag