Reputation: 8950
I'm encountering a stupid problem which I just cannot understand. How come that following piece of code:
public function getFormattedOffsetFrom($refTimezoneId = 'Europe/Paris', $format = 'G\hi') {
$timestamp = time();
$reference = new DateTime('@'.$timestamp);
$referenceTimeZone = new DateTimeZone($refTimezoneId);
$reference->setTimezone($referenceTimeZone);
$datetime = new DateTime('@'.$timestamp);
$datetime->setTimezone($this->timezone);
$offset = $this->timezone->getOffset($datetime) - $referenceTimeZone->getOffset($reference);
$prefix = '+';
if($offset < 0) {
$prefix = '-';
$offset = abs($offset);
}
return $prefix.date($format, $offset);
}
where $this->timezone is an instance of DateTimeZone positioned in Europe/Madrid, produces +1h00 when no args are specified ????
Paris and Madrid have no time offset. I just don't understand.
Thanks a lot for your help !!!! Florent
Upvotes: 1
Views: 500
Reputation: 29462
Why should be 0 ? Both Spain and France are using GMT+1 as time zone.
http://en.wikipedia.org/wiki/File:Time_zones_of_Europe.svg
The problem is that you are trying to format $offset
that holds time difference in seconds, with function date()
, which expects timestamp as second parameter. If the $offset == 0
date
function recognizes it as 1970-01-01 00:00:00 GMT, so in your timezone it will be 1970-01-01 01:00:00 GMT+1, and you are using format to return hours and minutes so that is why you have +1 as output.
You have to manually format this time difference like this:
$offsetH = floor( $offset / 3600 ); //full hours
$offsetM = floor(($offset - $offsetH) / 60 ); //full minutes
return sprintf("%s%sh%02s",$prefix,$offsetH,$offsetM) ;
Upvotes: 2
Reputation: 8612
The problem can be reduced to date('G', 0)
giving "1". Solution is to use gmdate()
.
Upvotes: 1