php-src icon indicating copy to clipboard operation
php-src copied to clipboard

DateTime::setTimestamp producing a DateTime that gives incorrect results during DST switch period

Open danhowardms opened this issue 4 years ago • 6 comments

Description

The following code:

<?php
date_default_timezone_set('Europe/London');
$ts = 1635641999;
$t = (new \DateTime())->setTimestamp($ts);
echo $t->format('r'), "\n";
echo $t->getTimestamp(), "\n";
echo ($ts === $t->getTimestamp() ? 'correct' : 'incorrect'), "\n\n";
$ts++;
$t = (new \DateTime())->setTimestamp($ts);
echo $t->format('r'), "\n";
echo $t->getTimestamp(), "\n";
echo ($ts === $t->getTimestamp() ? 'correct' : 'incorrect'), "\n\n";

Resulted in this output:

Sun, 31 Oct 2021 01:59:59 +0000
1635645599
incorrect

Sun, 31 Oct 2021 01:00:00 +0000
1635642000
correct

But I expected this output instead:

Sun, 31 Oct 2021 01:59:59 +0100
1635641999
correct

Sun, 31 Oct 2021 01:00:00 +0000
1635642000
correct

We get the incorrect timestamp during the daylight saving time switch for Europe/London.

At @1635641999 the time in Europe/London is 01:59:59, but at that time we are still in BST (GMT+0100), but the GMT difference reported by the DateTime format() function is incorrectly showing +0000. I would guess that the getTimestamp() function is giving a value that is incorrect by 3600 seconds for the same reason.

PHP Version

PHP 8.1.1

Operating System

No response

danhowardms avatar Jan 17 '22 15:01 danhowardms

Indeed, https://3v4l.org/TPqXM looks wrong. Also for me:

cmb@ELEPHPANT:~$ TZ=Europe/London date --date='@1635641999'
Sun Oct 31 01:59:59 BST 2021

cmb69 avatar Jan 17 '22 18:01 cmb69

This has already been reported as https://bugs.php.net/68549. Not sure which one to close as duplicate, since GH issues are preferable now, but the bugsnet ticket has PR #7639 referring to it. Also, this appears to be an upstream (timelib) issue.

cmb69 avatar Jan 17 '22 18:01 cmb69

It seems that the bug has already been reported in the timelib project here: https://github.com/derickr/timelib/issues/120, with a pull request here: https://github.com/derickr/timelib/pull/121 - but that was back in November and it hasn't been merged yet.

danhowardms avatar Jan 17 '22 20:01 danhowardms

The maintainer is likely busy otherwise. :|

cmb69 avatar Jan 17 '22 20:01 cmb69

Yup. But stay tuned.

derickr avatar Jan 19 '22 09:01 derickr

The timelib with this fix has now been merged, and the fix will be in PHP 8.1.7: https://github.com/php/php-src/commit/3d53e59b22818b07cc974047599186dbaec4bbde#diff-8a6f50552d89dfcad93fed8742e8160e6e74a521cc93e331701b784b3fa90ea7R391

derickr avatar May 27 '22 09:05 derickr