The predefined method of PHP - diff() lets us calculate the difference between two dates. We can get the difference between the days of two dates, two months and also two years.
This method is used as a method of the object because first, we store first date in a variable and then in that variable, pass the diff() method by using object operator ( -> ) for the second date in its parameter like this $first->diff($second);
Get the differences between two dates in years
<?php
$first = date_create("02-05-2000");
$second = date_create("02-05-2020");
$difference = $first->diff($second);
$y_difference = $difference->format("%y");
echo $y_difference;
?>
Get the differences between two dates in months
<?php
$first = date_create("02-05-2019");
$second = date_create("18-08-2020");
$difference = $first->diff($second);
$m_difference = $difference->format("%m");
echo $m_difference;
?>
This is the difference between only months of two dates. It does not return difference of years in months.
Therefore, you also need to calculate the difference of year and then multiply from 12. Then add it with the month's difference.
<?php
$first = date_create("02-05-2019");
$second = date_create("18-08-2020");
$difference = $first->diff($second);
$m_difference = $difference->format("%y")*12+$difference->format("%m");
echo $m_difference;
?>
Know the differences between two dates in days
<?php
$first = date_create("03-07-2019");
$second = date_create("18-05-2020");
$difference = $first->diff($second);
$d_difference = $difference->format("%a");
echo $d_difference;
?>
Publish A Comment