Find Days/ Months/ Years Difference Between Two Dates in PHP

09-06-2022
PHP

Here we dicuss two methods of finding difference between two dates in PHP.

Difference Between Two Dates in PHP

You may either need to find total difference of two dates as intervel or total difference like total seconds, minutes, or hours or days.

Find Intervel Between Two Dates in PHP


$date1 = new DateTime("2022-01-01 00:00:00");
$date2 = new DateTime("2023-06-03 05:30:55");

$difference = $date1->diff($date2);

$diff_in_seconds = $difference->s; //55 seconds
$diff_in_minutes = $difference->i; //30 minutes
$diff_in_hours   = $difference->h; //5 hours
$diff_in_days    = $difference->d; //2 days
$diff_in_months  = $difference->m; //5 months
$diff_in_years   = $difference->y; //1 years

//or use below function

function get_date_interval($date1, $date2, $interval = null) {
    $difference = $date1->diff($date2);
    switch ($interval) {
        case 'seconds':
            return $difference->s;
        case 'minutes':
            return $difference->i;
        case 'hours':
            return $difference->h;
        case 'days':
            return $difference->d;
        case 'months':
            return $difference->m;
        case 'years':
            return $difference->y;
        default:
            return $difference;
    }
}

Find Total Difference Between Two Dates in PHP


$date1 = strtotime("2022-01-01 00:00:00");
$date2 = strtotime("2023-06-03 05:30:55");

$total_seconds_diff 	= abs($date1-$date2); 			//  44775055 seconds
$total_minutes_diff 	= $total_seconds_diff/60; 		//  746250.91 minutes
$total_hours_diff   	= $total_seconds_diff/60/60;		//  12437.51 hours
$total_days_diff    	= $total_seconds_diff/60/60/24; 	//  518.22 days
$total_months_diff  	= $total_seconds_diff/60/60/24/30; 	//  17.27 months
$total_years_diff   	= $total_seconds_diff/60/60/24/365;     //  1.41 years

Print Date Difference in Years, Months and Days


$from_date 	= "2015-01-01";
$to_date 	= "2018-06-03";

$date_difference = abs(strtotime($from_date) - strtotime($to_date));

$years  = floor($date_difference / (365 * 60 * 60 * 24));
$months = floor(($date_difference - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
$days   = floor(($date_difference - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 *24) / (60 * 60 * 24));

echo $years." year,  ".$months." months and ".$days." days";