Reputation: 95
I am trying to change the TimeZone of my date from Europe/Berlin to UTC before storing in it into the DB.
When I use the setTimezone() method of the DateTime object, it changes the timezone property but not the date itself.
Example code :
$dt = new \DateTime();
var_dump($dt);
$dt->setTimezone(new \DateTimeZone('Indian/Comoro'));
var_dump($dt);
$dt->setTimezone(new \DateTimeZone('UTC'));
var_dump($dt);
And the result :
object(DateTime)#1479 (3) { ["date"]=> string(26) "2019-02-18 14:12:37.521579" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Berlin" }
object(DateTime)#1479 (3) { ["date"]=> string(26) "2019-02-18 14:12:37.521579" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Indian/Comoro" }
object(DateTime)#1479 (3) { ["date"]=> string(26) "2019-02-18 14:12:37.521579" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }
Berlin is UTC+1 and Comoro is UTC+3, but the date doesn't change.
I'm working with Symfony 4 on Vagrant. This test is made inside of a controller Is it possible that my Timezones are all set to +00 ? What kind of tests could I implement to find the cause of this problem ?
UPDATE This returns me an offset of 0 in my controller. It returns 3600 with php CLI.
$tz = new \DateTimeZone('Europe/Berlin');
var_dump($tz->getOffset(new \DateTime('now', new \DateTimeZone('UTC'))));
Upvotes: 1
Views: 684
Reputation: 95
The problem was from the tzdata package which worked well after updating. I had to restart apache to make it work in my app.
Upvotes: 2
Reputation: 36
Try this (assuming the date is set to Europe/Berlin timezone by default):
$dt = new \DateTime();
Pass through the timezone UTC:
$timezone = new \DateTimeZone('UTC');
we then need to get the offset.
$offset = $timezone->getOffset($dt);
lastly, modify the date using the offset:
$dt->modify($offset . 'seconds');
Upvotes: 0
Reputation: 3040
The timestamp value represented by the DateTime object is not modified when you set the timezone using this method. Only the timezone, and thus the resulting display formatting, is affected.
Upvotes: 0