convert gmt to australian central time in swift

To convert GMT to Australian Central Time in Swift, you can follow these steps:

  1. Create a DateFormatter instance:
main.swift
let dateFormatter = DateFormatter()
36 chars
2 lines
  1. Set the date format:
main.swift
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
49 chars
2 lines
  1. Set the timezone for the input date (In this case, the input date is in GMT):
main.swift
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
55 chars
2 lines
  1. Parse the input date to a Date instance:
main.swift
let date: Date = dateFormatter.date(from: "2022-05-12 09:30:00")!
66 chars
2 lines
  1. Create another DateFormatter instance to format the output date:
main.swift
let outputDateFormatter = DateFormatter()
42 chars
2 lines
  1. Set the output date format:
main.swift
outputDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
55 chars
2 lines
  1. Set the timezone for the output date (In this case, the output date will be in Australian Central Time):
main.swift
outputDateFormatter.timeZone = TimeZone(abbreviation: "ACT")
61 chars
2 lines
  1. Format the output date:
main.swift
let outputDateString: String = outputDateFormatter.string(from: date)
70 chars
2 lines

The outputDateString will contain the date string in Australian Central Time.

Here's the complete example:

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

let date: Date = dateFormatter.date(from: "2022-05-12 09:30:00")!

let outputDateFormatter = DateFormatter()
outputDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
outputDateFormatter.timeZone = TimeZone(abbreviation: "ACT")

let outputDateString: String = outputDateFormatter.string(from: date)

print(outputDateString) // Will print "2022-05-12 20:00:00"
498 chars
14 lines

gistlibby LogSnag