php / php/php-src

Wrong result from DateTimeImmutable::diff

未关闭
#13,341 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Bug Extension: date Status: Needs Triage
主要语言
C
星标
40.4k
派生
8.1k
平均合并
2 天 13 小时
30 天内合并 PR
96

描述

Description

If you execute this code, it produces an extremely weird result. The first DTI is 11 minutes after what we’re ->diff() ’ing against, but when in the America/Los_Angeles TZ, it produces a very strange result. Converting the first DTI to UTC then produces the expected difference of 11 minutes.

//Difference of -1 year, 11 months, 31 days, etc.
<?php
$invalid_result = (new \DateTimeImmutable('2024-01-31 17:00:00', new \DateTimeZone('America/Los_Angeles')))
    ->diff(new \DateTimeImmutable('2024-02-01 00:49:00'));

//Difference of 11 minutes
$correct_result = (new \DateTimeImmutable('2024-01-31 17:00:00', new \DateTimeZone('America/Los_Angeles')))
    ->setTimezone(new \DateTimeZone('UTC'))
    ->diff(new \DateTimeImmutable('2024-02-01 00:49:00'));

var_dump($invalid_result);
var_dump($correct_result);

$invalid_result Resulted in this output:

object(DateInterval)#3 (10) {
  ["y"]=>
  int(-1)
  ["m"]=>
  int(11)
  ["d"]=>
  int(31)
  ["h"]=>
  int(0)
  ["i"]=>
  int(11)
  ["s"]=>
  int(0)
  ["f"]=>
  float(0)
  ["invert"]=>
  int(1)
  ["days"]=>
  int(0)
  ["from_string"]=>
  bool(false)
}

But I expected this output instead:

object(DateInterval)#2 (10) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(0)
  ["h"]=>
  int(0)
  ["i"]=>
  int(11)
  ["s"]=>
  int(0)
  ["f"]=>
  float(0)
  ["invert"]=>
  int(1)
  ["days"]=>
  int(0)
  ["from_string"]=>
  bool(false)
}
PHP Version

PHP 8.1

Operating System

No response

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先复现所提供的 PHP 8.1 脚本,并比较使用和不使用 setTimezone('UTC') 时的 DateTimeImmutable::diff。跟踪 DateTimeImmutable::diff 的入口点和时区处理,然后添加覆盖,表明 America/Los_Angeles 情况会产生预期的 11 分钟间隔。

由索引模型根据 Issue 内容生成。

评估

技术栈
php
领域
backend
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。