php date_diff 问题

php issue with date_diff

我正在尝试计算两个日期之间的月数,假设日期介于 2018-08-27 和 2018-10-10 之间。我想要的是一个基于这些日期的函数 return 相差 3 个月,08,09,10。我有下面的功能,但是好像只输出1个月;

public function getGraphMonthsCount(){

        $now =  '2018-08-27';
        $then = '2018-10-10';

        $newNow = new DateTime($now);
        $newThen =  new DateTime($then);

        $result = $newNow->diff($newThen)->m;

        return $result;
    }

此 return 值为 1。

这是 diff 函数在没有 ->m 参数的情况下输出的结果

object(DateInterval)#157 (15) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(1)
  ["d"]=>
  int(13)
  ["h"]=>
  int(0)
  ["i"]=>
  int(0)
  ["s"]=>
  int(0)
  ["weekday"]=>
  int(0)
  ["weekday_behavior"]=>
  int(0)
  ["first_last_day_of"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  int(44)
  ["special_type"]=>
  int(0)
  ["special_amount"]=>
  int(0)
  ["have_weekday_relative"]=>
  int(0)
  ["have_special_relative"]=>
  int(0)
}

我不知道为什么它只提供 13 个 'd' 和 1 个 'm',但如果你进一步查看对象,你会发现它确实有正确数量的 'days'

有更好的方法吗?

What i want is a function based on those dates to return a difference of 3 months

您可以尝试这样的操作:

$newNow = new DateTime($now);
$newNow = $newNow->modify('first day of this month');

$newThen = new DateTime($then);
$newThen = $newThen->modify('first day of next month');

$result = $newNow->diff($newThen)->m;

测试结果:

$now =  '2018-08-27';
$then = '2018-10-10';
// 3

$now =  '2018-08-10';
$then = '2018-08-27';
// 1