Reputation: 2346
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.
Upvotes: 4
Views: 1638
Reputation: 864
I came here looking for a way to get the offset between PHP's current default timezone and UTC. I went down the rabbit hole with DateTimeZone::getOffset
, but it turns out there's a much easier way:
$offset = date('O');
// Returns a string like '-0400'
$offset = date('P');
// Returns a string like '-04:00'
$offset = date('Z');
// Returns the offset in seconds, e.g. '-14400'
To be clear, this gets whatever the timezone offset is right now, but I imagine that's what is wanted most of the time.
You can switch PHP's current timezone with date_default_timezone_set()
.
See https://www.php.net/manual/en/datetime.format.php
Upvotes: 0
Reputation: 522636
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.
Upvotes: 6