I got this line of code:
echo (new DateTimeZone('UTC'))->getOffset(new DateTime('now', new DateTimeZone('America/New_York')));
It returns zero. But I expected it to return the difference between UTC and America/New_York time zones.
I then provided the same time zone twice:
echo (new DateTimeZone('America/New_York'))->getOffset(new DateTime('now', new DateTimeZone('America/New_York')));
I expected it to return zero because the time zones are the same. But it now returns -18000 (That's the offset between America/New_York and UTC).
In the documentation it says that getOffset() always returns the offset to GMT (=UTC). But then why is getOffset not static? And if it is always the offset relative to GMT why does the time zone in the first constructor play a role?
I know there's another getOffset method in the DateTime class which is easier to use. But i want to understand how the getOffset method in the DateTimeZone class works.
The offset of a timezone is how many hours it differs from UTC. The offset of a timezone may change throughout the year depending on when DST goes into and out of effect. So you cannot get the offset of a timezone just like that, since it's not a constant value. You can only interrogate a timezone what its offset from UTC is at a given time. That's what you pass the DateTime
object to getOffset
for: to ask the timezone what its offset value is for the given time. E.g.:
echo (new DateTimeZone('America/New_York'))->getOffset(new DateTime), PHP_EOL;
echo (new DateTimeZone('America/New_York'))->getOffset(new DateTime('+6 months'));
-18000
-14400
If you want to get the offset difference between two arbitrary timezones, you get their respective UTC offsets and subtract them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With