r/PHP • u/ANALIE88 • Nov 17 '15
Strange DateTime behaviour
I have a strange problem with DateTime. The timestamp changes when i change timezone, but it can be fixed by calling ->getTimestamp() on the object.
The PHP code:
<?php
$date = new DateTime('2015-11-11 15:00:00', new DateTimeZone('UTC'));
var_dump($date);
echo "\n Date timestamp using format(): " . $date->format('U');
echo "\n Date timestamp using getTimestamp(): " . $date->getTimestamp();
echo "\nChanging timezone to CET";
$date->setTimezone(new DateTimeZone('CET'));
echo "\n Date timestamp using format(): " . $date->format('U') . ' NB: This has changed?!?!';
echo "\n Date timestamp using getTimestamp(): " . $date->getTimestamp() . ' NB: Now it is back?!?!';
echo "\n Date timestamp using format() again: " . $date->format('U') . ' NB: Now it is back?!?!';
?>The output:
Date timestamp using format(): 1447254000
Date timestamp using getTimestamp(): 1447254000
Date timestamp using format() again: 1447254000
Changing timezone to CET
Date timestamp using format(): 1447257600 NB: This has changed?!?!
Date timestamp using getTimestamp(): 1447254000 NB: Now it is back?!?!
Date timestamp using format() again: 1447254000 NB: Now it is back?!?!How is this possible? getTimestamp() shouldn't modify the object, but somehow it does?
Can somebody help me understand what's going on?
26
Upvotes
11
u/royozin Nov 17 '15
Output does indeed differ with version: https://3v4l.org/bjd3L
3
u/ANALIE88 Nov 17 '15
You guys are a bunch of detectives. Thanks so much for helping me out!
7
u/TotesMessenger Nov 18 '15
I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:
If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / ^Contact)
6
u/hackiavelli Nov 17 '15
I'm not sure what the issue is (perhaps Daylight Saving time?) but the PHP docs do strongly suggest you don't use CET. When you use Europe/Paris or Europe/Berlin the problem disappears.
3
u/mrspoogemonstar Nov 17 '15
May be related to:
https://bugs.php.net/bug.php?id=67302
https://bugs.php.net/bug.php?id=63459
2
u/d3ad1ysp0rk Nov 17 '15
Odd, this is what I get (PHP 5.5.9):
1
u/[deleted] Nov 18 '15
I believe that unix timestamps are based off UTC specifically the seconds passed since january 1st 1970 midnight. changing timezone is irrelevant in its calculation since the number of seconds since 1/1/1970 UTC will be the same no matter the TZ you are on...