PHP 日期时间设置时区 2038

标签 php datetime timestamp year2038

我在项目中使用 DateTime 转换所有日期(从 UTC 到欧洲/维也纳)。现在我的日期超过 2038,但无法获取正确的时间。

示例代码:

$met = new DateTimeZone('Europe/Vienna');
$utc = new DateTimeZone('UTC');

$date = new DateTime('2043-08-04 08:00:00', $utc);
$date->setTimezone($met);
echo $date->format('Y-m-d H:i:s'); // Output is: 2043-08-04 09:00:00 instead of 2043-08-04 10:00:00

由于“夏令时”,2043-03-29 和 2043-10-25 之间需要计算距 UTC +2 小时的时间。

如果我将 2043-08-04 08:00:00 更改为 2037-08-04 08:00:00 我会得到正确的时间。

我知道这是整数 32 位的 2038 问题,但如何将整数 64 位与 DateTime setTimezone 函数一起使用?

谢谢

最佳答案

如果问题与溢出的 32 位 Unix 时间戳有关,您将得到 1970 年左右的日期以及类似的完全错误的结果。然而,您的结果仅相差一小时。事实上,我们可以认为小时是正确的,因为您只是得到了错误的时区偏移,正如您在打印时区信息时所看到的那样:

var_dump($date);
echo $date->format('c');
object(DateTime)#3 (3) {
  ["date"]=>
  string(26) "2043-08-04 09:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(13) "Europe/Vienna"
}
2043-08-04T09:00:00+01:00

这表明内部时间数据库缺少 2043 年的信息,就像当年的信息一样。我们可以通过以下方式进一步确认这一点:

$met = new DateTimeZone('Europe/Vienna');
var_dump($met->getTransitions((new DateTime('2017-01-01'))->format('U'), (new DateTime('2017-12-31'))->format('U')));
var_dump($met->getTransitions((new DateTime('2043-01-01'))->format('U'), (new DateTime('2043-12-31'))->format('U')));

此代码(显然需要在 32 位平台上运行)打印:

array(3) {
  [0]=>
  array(5) {
    ["ts"]=>
    int(1483225200)
    ["time"]=>
    string(24) "2016-12-31T23:00:00+0000"
    ["offset"]=>
    int(3600)
    ["isdst"]=>
    bool(false)
    ["abbr"]=>
    string(3) "CET"
  }
  [1]=>
  array(5) {
    ["ts"]=>
    int(1490490000)
    ["time"]=>
    string(24) "2017-03-26T01:00:00+0000"
    ["offset"]=>
    int(7200)
    ["isdst"]=>
    bool(true)
    ["abbr"]=>
    string(4) "CEST"
  }
  [2]=>
  array(5) {
    ["ts"]=>
    int(1509238800)
    ["time"]=>
    string(24) "2017-10-29T01:00:00+0000"
    ["offset"]=>
    int(3600)
    ["isdst"]=>
    bool(false)
    ["abbr"]=>
    string(3) "CET"
  }
}
array(1) {
  [0]=>
  array(5) {
    ["ts"]=>
    int(2303679600)
    ["time"]=>
    string(24) "2042-12-31T23:00:00+0000"
    ["offset"]=>
    int(3600)
    ["isdst"]=>
    bool(false)
    ["abbr"]=>
    string(3) "CET"
  }
}

据 PHP 所知,2043 年是欧洲中部时间 (CET),从 1 月到 12 月。

此信息来自Olson database :

a collaborative compilation of information about the world's time zones, primarily intended for use with computer programs and operating systems

PHP 手册包括 instructions to update it ,以防它已经有丢失的数据。如果没有,您可能不走运。

关于PHP 日期时间设置时区 2038,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42931978/

相关文章:

python - 如何将此日期转换为 python 日期时间对象?

mysql - 这是检查时间戳/日期时间是否属于指定日期的最佳方法

javascript - 我如何知道我点击了 HTML 中的哪个链接

c# - 时区转换和夏令时

PHP fopen 权限被拒绝 - Windows Server 远程

R - 使用 HHMMSS 格式将日期和时间字段转换为 POSIXct

c++ - 从 PostgreSQL DB 和 Linux 转移 C/C 中的时间戳?

java - 由于时区不同导致时间戳时间不匹配

javascript - 带有远程结果和缓存的 jQuery 类别搜索

php - 如何在 .htaccess 中为 'pagename/id' 设置重写规则?