简体   繁体   中英

PHP Carbon set timezone offset adds hours

I have a carbon object new Carbon and then call ->setTimezone() method on it.

When I call the method with the value of a timezone string such as Europe/London , I can call the method as many times as I want with no issue.
However if I call it with the value of +02:00 , every time the method is called it adds 2 hours to the time. It only happens for none type 3 time zones.
Why does this happen and how can I fix it?

Code showing problem:

$c = new Carbon()

=> Carbon\Carbon {#1942
     +"date": "2018-01-04 14:21:57.000000",
     +"timezone_type": 3,
     +"timezone": "UTC",
   }

$c->setTimezone('+02:00')->setTimezone('+02:00')->setTimezone('UTC')

=> Carbon\Carbon {#1942
     +"date": "2018-01-04 18:21:57.000000",
     +"timezone_type": 3,
     +"timezone": "UTC",
   }

This is a bug in PHP ( https://bugs.php.net/bug.php?id=72338 ) that was fixed in PHP 7 (7.0.17 and 7.1.3).

If you're stuck on an earlier version there's a workaround mentioned in the comments to the bug report, namely calling getTimestamp() between setTimezone() methods.

$utc = new DateTimeZone('UTC');
$plus200 = new DateTimeZone('+02:00');

$date = new DateTime('2018-06-14 09:15:00', $utc);

echo $date->format('Y-m-d H:i:s'); // 2018-06-14 09:15:00

$date->setTimezone($plus200);
$date->setTimezone($plus200);
$date->setTimezone($utc);

echo $date->format('Y-m-d H:i:s'); // 2018-06-14 13:15:00

$date = new DateTime('2018-06-14 09:15:00', $utc);

$date->getTimestamp();
$date->setTimezone($plus200);
$date->getTimestamp();
$date->setTimezone($plus200);
$date->getTimestamp();
$date->setTimezone($utc);

echo $date->format('Y-m-d H:i:s'); // 2018-06-14 09:15:00

Test script with output from various versions: https://3v4l.org/cXZYC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM