String Date to Date

From apple docs:

let isoDate = "2022-12-14T04:30:00+05:30"

let fixedFormatter = DateFormatter()
fixedFormatter.locale = Locale(identifier: "en_US_POSIX")
fixedFormatter.timeZone = TimeZone(secondsFromGMT: 0)
fixedFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"

let date = fixedFormatter.date(from: isoDate)!

let displayFormatter = DateFormatter()
displayFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
// uses current locale and current time zone
// overriding those, for test
displayFormatter.locale = Locale(identifier: "en_US_POSIX")
displayFormatter.timeZone = TimeZone(secondsFromGMT: (5*60+30)*60)
let dateString = displayFormatter.string(from: date)

print("date: \(date)") // 2022-12-13 23:00:00 +0000
print("dateString: \(dateString)") // 2022-12-14T04:30:00GMT+05:30

Note:

The reason for this warning is unknown to me but I would not ignore it.

Also there are a newer FormatStyle and ParseableFormatStyle (macOS 12 and later, iOS 15 and later)

1 Like