String Date to Date

Hi, I'm trying to convert my String Date to a Date, but it's displaying the wrong time

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

let currentDateFormatter = DateFormatter()
currentDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let initDate = currentDateFormatter.date(from:isoDate)!
print("initDate: \(initDate)") // prints initDate: 2022-12-13 23:00:00 +0000

The timezone in the string date is GMT+5:30 so I'd expect my date to also be the same, however it comes back as GMT.

From the code above isoDate != initDate

What am I misunderstanding?

Thanx in advance!

Dates don't know about time zones. It's useful to know that a Date object is really just a wrapper around a Double number of seconds after some reference date. Clearly, such a number wouldn't know anything about time zones.

fun little demo

Obviously, don't actually rely on this implementation detail, but it's neat to see:

import Foundation

let d = Date()

// The exact number will depend on when you run this code, but it'll give the same result
print(d.timeIntervalSinceReferenceDate)  // => 692674495.061181
print(unsafeBitCast(d, to: Double.self)) // => 692674495.061181

The timezone is a layer of interpretation of this number, imposed by the presentation layer (in this case, print, which always prints a timestamp in your local timezone).

See Date in Swift printed is wrong | Apple Developer Forums

1 Like

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