I'm trying to find the difference between two dates and display it in months.
$currentDate = date_create(date('Y-m-d'));
$expiryDate = date_create('2022-12-10');
$dateDiff = date_diff($currentDate, $expiryDate);
$formattedDateDiff = $dateDiff->format('%m');
When I var_dump($formattedDateDiff)
it just returns 0. Changing the $expiryDate
reveals that it seems to be giving the leftover months after the years, i.e. if the expiry date was '2022-01-10'
, it would give 1, as there's 3 years and 1 month between now and then, whereas I want the full 37 months.
When I var_dump($dateDiff)
to see what it is that I'm actually formatting, it returns the following:
object(DateInterval)#830 (16) {
["y"]=>
int(3)
["m"]=>
int(0)
["d"]=>
int(0)
["h"]=>
int(0)
["i"]=>
int(0)
["s"]=>
int(0)
["f"]=>
float(0)
["weekday"]=>
int(0)
["weekday_behavior"]=>
int(0)
["first_last_day_of"]=>
int(0)
["invert"]=>
int(0)
["days"]=>
int(1096)
["special_type"]=>
int(0)
["special_amount"]=>
int(0)
["have_weekday_relative"]=>
int(0)
["have_special_relative"]=>
int(0)
}
So it's obviously expecting every relevant unit to be displayed, rather than just one. Is there a way to return the total number of months in the $dateDiff
object, rather than just the leftover months? I could just divide the days by 30, but that seems like such a naff way around it, and wouldn't exactly be the most accurate what with differing lengths of months and such.