2

I've been trying to research how to do this and I've come to my last option SO.

I only saw getting the difference of dates in days but I need to get the number of months.

if I do this

$date1 = new DateTime(date('Y-m-d'));
$date2 = new DateTime(date('2013-04-10'));
$interval = $date2->diff($date1);

$interval->format("%m months");

I get 7 months which is wrong because it is last year so the value must be 19 months.

Kevin
  • 41,694
  • 12
  • 53
  • 70
eaponz
  • 574
  • 1
  • 16
  • 32
  • 2
    19 months = 1 year + 7 months, i.e. `$interval->y * 12 + $interval->m`. – Ja͢ck Nov 16 '14 at 13:10
  • **Check this link it will help you :** [http://stackoverflow.com/questions/4233605/elegant-way-to-get-the-count-of-months-between-two-dates][1] [1]: http://stackoverflow.com/questions/4233605/elegant-way-to-get-the-count-of-months-between-two-dates – Debug Diva Nov 16 '14 at 13:40

1 Answers1

3

Actually, when you print_r() the interval object, you'll see this:

DateInterval Object
(
    [y] => 1
    [m] => 7   // that 7 months is just a component of it
    [d] => 6
    [h] => 14
    [i] => 12
    [s] => 9
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 0
    [days] => 585
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)

// its 1 year 7 months

To convert it:

$date1 = new DateTime(); // no need to put `date(Y-m-d)` just create that object, its already undestood its today
$date2 = new DateTime('2013-04-10');
$interval = $date2->diff($date1);

echo '<pre>' . print_r($interval, true) . '</pre>';

$months = $interval->m + ($interval->y * 12);
echo $months;
Kevin
  • 41,694
  • 12
  • 53
  • 70