为什么两个 DateTime 对象之间的差异不起作用?

Why the difference between two DateTime objects does not work?

我的"DateTime difference code"有问题:

$timeStart = new DateTime('2015-11-28');
$timeEnd = new DateTime('2016-11-28');
$interval = $timeEnd->diff($timeStart);
$result = $interval->format('%d');

echo $result." day(s)";

当我可视化 $result 时,PHP 显示 0。但是这两个日期之间的天数多于 0 天...

php不计算两个不在同一年的日期的差值?

因为相差0天。但是有1年的差异。如果您将 %d 更改为 %y,您将得到 1。因此存在 1 年、0 个月和 0 天的差异。

您可以使用 DateInterval 上的 days 属性,例如:

$result = $interval->days;

好的,我知道答案已经给出了。不过下面只是稍微解释一下。

事实上,当你有固定的时间(年、月、日、小时)时,DateInterval::format() 确实有意义,就像这样:

$interval = new DateInterval('P2Y4DT6H8M');
echo $interval->format('%d days');

那不是你的情况!
你有一个相对时间(2016-11-28 与 2015-11-28 相关)。在这种特定情况下,您需要自 2015 年 11 月 28 日以来过去的天数。
这就是为什么 DateInterval::days (DateTime::diff() returns a DateInterval object) 有意义:

$start = new DateTime('2015-11-28');
$end   = new DateTime('2016-12-28');

var_dump($end->diff($start)->days);