PHP date_diff 不考虑年份

PHP date_diff not considering the year

我 运行 下面的代码预计月份的差异是 12,但我得到的是 0。并且阅读手册我找不到这样做的方法。

    $from = date_create_from_format('m/d/Y', '01/01/2017');
    $to = date_create_from_format('m/d/Y', '01/01/2018');
    die(date_diff($from, $to)->format('%m'));

结果是对的,但没有考虑年份。我应该为 date_diff 添加任何额外的参数来考虑年份吗?[=​​16=]

因为 DateInterval::format() 不会重新计算时间字符串或日期段中的结转点,您可以改为执行以下操作,将年份乘以 12 个月,然后加上任何剩余的月份:

$from = date_create_from_format('m/d/Y', '01/01/2017');
$to = date_create_from_format('m/d/Y', '01/01/2018');
$interval = date_diff($from, $to);
echo $interval->m + 12*$interval->y; // 12

示例:http://sandbox.onlinephpfunctions.com/code/628292d8d0f1ea00e2086b3de059c2e913b1af7d

The DateInterval::format() method does not recalculate carry over points in time strings nor in date segments. This is expected because it is not possible to overflow values like "32 days" which could be interpreted as anything from "1 month and 4 days" to "1 month and 1 day". http://php.net/manual/en/dateinterval.format.php