I'm really struggling with dates and timezones.
My understanding is Date
is independent of timezone and is just a point in time.
I'm writing a unit test and I want to create a Date
object that would represent the time now if the user was in a different timezone than the default London zone I'm running the test from and then convert it to a different timezone.
I start off by creating a Date
object using DateComponents
with the projected time, in this example, I want Australia/Sydney
time which is 11hrs ahead of GMT (my location).
Next, I want to derive a new Date
that is adjusted back to GMT i.e. essentially subtracting 11hrs.
The derived date I want is 2022-12-07 13:30:00 +0000
. I'm using dateComponents(in:from:)
method on Calendar
to specify the timezone, according to Apple's documentation:
Returns all the date components of a date, as if in a given time zone (instead of the Calendar time zone).
I then set the timeZone component which should then adjust the time from Australia/Sydney
to Europe/London
but while it's adjusting the time it's not correctly adjusting the date component which should be shifted one day back.
Here is my code example:
let components = DateComponents(
year: 2022,
month: 12,
day: 8,
hour: 02,
minute: 30,
second: 0
)
let originalDate = Calendar.current.date(from: components)!
// originalDate printed is 2022-12-08 02:30:00 +0000
var components = Calendar.current.dateComponents(in: TimeZone(identifier: "Australia/Sydney")!, from: originalDate)
components.timeZone = TimeZone(identifier: "Europe/London")!
let localTime = components.date!
// localTime printed is 2022-12-08 13:30:00 +0000 but I expected 2022-12-07 13:30:00 +0000 as Sydney is +11hrs ahead of GMT+0.