英文:
PHP - date modify returned negative Microseconds
问题
出现罕见情况,微秒日期时间变为负数。
$next_datetime = date_create()->modify('-500 ms')->format("Y-m-d H:i:s.u");
// 输出 "2023-05-30 18:57:50.-99999"
在运行 PHP 8.1 时发生。
有人能解释一下吗?
*** 更新 ***
只有在日期时间的微秒部分设置为 1 时才会发生。
$datetime_before = date_create('now');
$datetime_before->setTime(1,1,1,1 /* 如果设置为其他任何数字,就可以正常工作 */);
$datetime_after = clone($datetime_before);
$datetime_after->modify('-100 ms');
$string = $datetime_after->format('Y-m-d H:i:s.u');
if (str_contains($string, "-999")) {
echo 'before: ';
var_dump($datetime_before);
echo PHP_EOL;
echo 'after: ';
var_dump($datetime_after);
echo PHP_EOL;
exit;
}
输出
before: object(DateTime)#51 (3) { ["date"]=> string(26) "2023-06-02 01:01:01.000001" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/London" } after: object(DateTime)#52 (3) { ["date"]=> string(26) "2023-06-02 01:01:01.-99999" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/London" }
示例:
https://3v4l.org/YDEq2#v8.1.19
英文:
It appears that rarely I'm getting a negative microseconds datetime.
$next_datetime = date_create()->modify('-500 ms')->format("Y-m-d H:i:s.u");
// Output "2023-05-30 18:57:50.-99999"
Running PHP 8.1
Can anyone explain this?
*** UPDATE ***
This only happens when the datetime microseconds is set to one.
`
$datetime_before = date_create('now');
$datetime_before->setTime(1,1,1,1 /* If set to any other number, it works fine */);
$datetime_after = clone($datetime_before);
$datetime_after->modify('-100 ms');
$string = $datetime_after->format('Y-m-d H:i:s.u');
if (str_contains($string, "-999")) {
echo 'before: ';
var_dump($datetime_before);
echo PHP_EOL;
echo 'after: ';
var_dump($datetime_after);
echo PHP_EOL;
exit;
}
`
Output
before: object(DateTime)#51 (3) { ["date"]=> string(26) "2023-06-02 01:01:01.000001" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/London" } after: object(DateTime)#52 (3) { ["date"]=> string(26) "2023-06-02 01:01:01.-99999" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/London" }
Example:
https://3v4l.org/YDEq2#v8.1.19
答案1
得分: 1
这是一个错误(GH-11368),已在PHP/8.2.9中修复(于2023年8月3日发布)。
答案2
得分: -2
根据 https://www.php.net/manual/en/datetime.formats.time.php 我认为你的时间格式是错误的。"ms" 似乎不是支持的格式的一部分。在你的情况下,你可能需要使用 "frac"。
我猜想PHP可能会将它解释为月份和闰秒。
英文:
Based on https://www.php.net/manual/en/datetime.formats.time.php I think your time format is wrong. ms is something that doesn’t seem to be part of a supported format. On your case you would need frac
My guess would be that php would interpret it as month and leap seconds.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论