-3

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?

grhmstwrt
  • 341
  • 1
  • 6
  • 20
  • Possible duplicate of [How to get the number of days of difference between two dates on mysql?](https://stackoverflow.com/questions/2490173/how-to-get-the-number-of-days-of-difference-between-two-dates-on-mysql) – Sanu0786 Oct 25 '18 at 12:21
  • Thanks - will check that out – grhmstwrt Oct 25 '18 at 12:26
  • As indicated in your result, the difference between the two dates is 1 month and 13 days. How is that wrong? – Nick Oct 25 '18 at 12:40
  • Thanks for the comments, this function wasn't outputted what i wanted, i wanted the difference in months between the two dates, not the amount of days – grhmstwrt Oct 25 '18 at 12:50

1 Answers1

2

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
hausl
  • 160
  • 16