PHP Difference Between Two Dates In Years, Months And Days
To calculate the difference between two dates in years, months and days in PHP, we have to use three functions
- strtotime() function
- floor() function()
- abs() function
Read Here, strtotime, floor and abs functions in PHP
Let us consider two dates and store in variables.
$date1 = ‘2016–06–01’;
$date2 = ‘2020–08–08’;
Now, the difference between these two dates will be
$diff = abs(strtotime($date2)-strtotime($date1));
To calculate the year, divide the difference by total seconds in the year that is 365*60*60*24
Now, the year between these two dates will be
$years = floor($diff / (365*60*60*24));
To calculate the month, subtract the year from the date difference and divide the result by total seconds in a month that is 30*60*60*24
Now, the month between these two dates will be
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
To calculate the day, subtract the date difference from the year and month and divide the result by total seconds in a day that is 60*60*24
Now, the days between these two dates will be