'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.
Solution 1:[1]
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().
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
