Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone tell me how the DateTimeZone::getOffset PHP function works?

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.

like image 468
zomega Avatar asked Sep 21 '25 03:09

zomega


1 Answers

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.

like image 89
deceze Avatar answered Sep 22 '25 16:09

deceze