Reputation: 2619
I can't figure out how timezones work. Why this code produces zero as ouput? Shouldn't it return 10800 instead of 0?
$myZone = new DateTimeZone('+0300');
$utcZone = new DateTimeZone('+0000');
$dateA = new DateTime('now', $myZone);
var_dump($utcZone->getOffset($dateA)); // 0
$dateA->setTimezone($utcZone);
var_dump($utcZone->getOffset($dateA)); // 0
$dateA->modify('+ 3600 seconds');
var_dump($utcZone->getOffset($dateA)); // 0
It seems like $utcZone->getOffset(...) does not care about it's argument timezone and time diff at all. Where is the logic?
Upvotes: 1
Views: 280
Reputation: 11
getOffset
returns the offset used by the timezone at a specific moment.
Timezones can have more than one offset during history - the most common case is Daylight Saving Time, when the offset changes for a specified period. So depending on the time of the year, a certain timezone can have a different offset.
The datetime parameter defines the instant you want to check, and getOffset
will check in the timezone's history and return the one used at that specific datetime - no matter what the datetime's timezone is. In the documentation you can find an example of that: http://php.net/manual/en/datetimezone.getoffset.php#refsect1-datetimezone.getoffset-examples
That said, when you use fixed offset values such as "+0000", this means that the DateTimeZone
object will always have that offset, all the time - it never changes. That's why when you call $utcZone->getOffset
, it always returns zero, no matter what datetime parameter you pass.
If you want the date's offset, call the getOffset
method on the DateTime
object.
Upvotes: 1
Reputation: 8358
<?php
$myZone = new DateTimeZone('+0300');
$utcZone = new DateTimeZone('+0000');
$dateA = new DateTime('now', $myZone);
$timeOffset = $myZone->getOffset($dateA);
var_dump($timeOffset);
This one will return 10800 as you said. It was the other way around in getOffset
.
output is : int(10800)
Upvotes: 1