Last active
March 30, 2018 04:38
-
-
Save pwm/77ae29358077e9d543912dff9e99324d to your computer and use it in GitHub Desktop.
Datetimes are hard to get right...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* The timezone in these datetimes look the same but they are in fact represent different UTC offsets. | |
* The 1st one maps to UTC+01 (BST) while the 2nd one maps to a UTC+00 (GMT). | |
* This is because daylight saving time (DST) aka. clocks going forward/backward happen on different days in different years. | |
*/ | |
$now = new DateTime('2018-03-26T08:00:00', new DateTimeZone('Europe/London')); | |
$inAYear = new DateTime('2019-03-26T08:00:00', new DateTimeZone('Europe/London')); | |
echo $now->format(DATE_ATOM) . PHP_EOL; // 2018-03-26T08:00:00+01:00 | |
echo $inAYear->format(DATE_ATOM) . PHP_EOL; // 2019-03-26T08:00:00+00:00 | |
echo $now->getTimezone()->getOffset($now) . PHP_EOL; // 3600 | |
echo $inAYear->getTimezone()->getOffset($inAYear) . PHP_EOL; // 0 | |
/* | |
* If we set both timezone values to an absolute UTC+01 offset then the 1st one generates a valid | |
* Europe/London BST datetime, however, the second one is not a valid Europe/London datetime | |
* as on that datetime Europe/London maps to UTC+00 (GMT). | |
*/ | |
$now = new DateTime('2018-03-26T08:00:00+01:00'); | |
$inAYear = new DateTime('2019-03-26T08:00:00+01:00'); // not valid Europe/London | |
echo $now->format(DATE_ATOM) . PHP_EOL; // 2018-03-26T08:00:00+01:00 | |
echo $inAYear->format(DATE_ATOM) . PHP_EOL; // 2019-03-26T08:00:00+01:00 | |
echo $now->getTimezone()->getOffset($now) . PHP_EOL; // 3600 | |
echo $inAYear->getTimezone()->getOffset($inAYear) . PHP_EOL; // 3600 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment