简体   繁体   English

php date_diff 问题

[英]php issue with date_diff

I'm trying to figure out the number of months between two dates, the dates hypothetically lets say are between 2018-08-27 and 2018-10-10.我试图找出两个日期之间的月数,假设日期在 2018-08-27 和 2018-10-10 之间。 What i want is a function based on those dates to return a difference of 3 months, 08,09,10.我想要的是一个基于这些日期的函数来返回 3 个月、08、09、10 的差异。 I have the following function, but it only seems to output 1 month;我有以下功能,但它似乎只输出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;
    }

this return a value of 1.这返回值 1。

this is what the diff function outputs without the ->m param这是 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)
}

I don't know why it's providing only 13 'd' and 1 'm', but if you look further into the obj you can see it does have the correct amount of 'days'我不知道为什么它只提供 13 个“d”和 1 个“m”,但是如果您进一步查看 obj,您会发现它确实具有正确的“天数”

Is there a better way of doing this?有没有更好的方法来做到这一点?

What i want is a function based on those dates to return a difference of 3 months我想要的是一个基于这些日期的函数来返回 3 个月的差异

You can try something like this:你可以尝试这样的事情:

$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;

Test results:检测结果:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM