PHP 函数 strftime()
和 gmstrftime()
返回格式为 "%s"
的(不同的)错误结果。我使用 CLI 和 Apache (OpenSuse) 使用 PHP 5.5.14 和 PHP 7.2.5 对其进行了测试。我使用带和不带 DST 的时间戳。
我的问题:你能用其他版本/系统确认这个错误吗?
测试脚本
<?PHP
header('Content-Type: text/plain; charset=utf-8');
$list = array(
1546303600, // 2018-01-01 00:46:40 UTC
1556703600, // 2019-05-01 09:40:00 UTC
);
echo "\ndate_default_timezone_set('UTC')\n";
date_default_timezone_set('UTC');
foreach ( $list as $time )
{
printf("\n%u\n%4s\n%s\n",
$time,
strftime('%s, %F %T %Z',$time),
gmstrftime('%s, %F %T %Z',$time) );
}
echo "\ndate_default_timezone_set('Europe/Berlin')\n";
date_default_timezone_set('Europe/Berlin');
foreach ( $list as $time )
{
printf("\n%u\n%4s\n%s\n",
$time,
strftime('%s, %F %T %Z',$time),
gmstrftime('%s, %F %T %Z',$time) );
}
?>
错误的结果
%s
应该返回原始时间戳,但它没有。结果相差 1 小时(3600 秒)。
date_default_timezone_set('UTC')
1546303600
1546300000, 2019-01-01 00:46:40 UTC <<< WRONG!
1546300000, 2019-01-01 00:46:40 GMT <<< WRONG!
1556703600
1556700000, 2019-05-01 09:40:00 UTC <<< WRONG!
1556700000, 2019-05-01 09:40:00 GMT <<< WRONG!
date_default_timezone_set('Europe/Berlin')
1546303600
1546303600, 2019-01-01 01:46:40 CET
1546300000, 2019-01-01 00:46:40 GMT <<< WRONG!
1556703600
1556703600, 2019-05-01 11:40:00 CEST
1556700000, 2019-05-01 09:40:00 GMT <<< WRONG!
我已经向 bugs.php.net 报告了这个错误:https://bugs.php.net/bug.php?id=77840
一些说明(编辑)
PHP 文档告诉我们:“%s
给出与 time()
相同的结果”。这个结果与时区无关(自纪元以来的秒数)。所以 strftime("%s",ANY_TIME)
必须返回 ANY_TIME
。 gmstrftime()
也是如此。
Unix 工具日期按预期工作:
date '+%s %F %T' -d@1556703600
date -u '+%s %F %T' -d@1556703600
TZ=UTC date '+%s %F %T' -d@1556703600
结果是:
1556703600 2019-05-01 11:40:00
1556703600 2019-05-01 09:40:00
1556703600 2019-05-01 09:40:00
所以这不是底层C函数的问题!
最佳答案
差异似乎取决于时区的设置方式。下面的测试将向您展示,无论使用 date_default_timezone_set
设置什么,strftime 都认为存在 UTC 偏移量。
date_default_timezone_set("UTC");
echo strftime("%s %z", 1546303600);
date_default_timezone_set("America/Vancouver");
echo strftime("%s %z", 1546303600);
The code似乎应用了从系统时区派生的偏移量,因此您可以尝试这样做:
putenv("TZ=UTC");
echo strftime("%s %z", 1546303600);
它应该可以工作。根据the documentation they've provided ,这显然是不正确的行为。
关于php - strftime() 和 gmstrftime() 返回 "%s"的错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55502396/