Search code examples
phpdatedatediff

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. What i want is a function based on those dates to return a difference of 3 months, 08,09,10. I have the following function, but it only seems to output 1 month;

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.

this is what the diff function outputs without the ->m param

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'

Is there a better way of doing this?


Solution

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

    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