Current Article:

How to calculate the difference between two dates using PHP?

How to calculate the difference between two dates using PHP?

PHP has DateTime and DateInterval objects which can be used like this:

$date1 = new DateTime("2024-03-24");
$date2 = new DateTime("2025-05-08");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";

// shows the total amount of days (not divided into years, months and days like above)
echo "difference " . $interval->days . " days ";

Also, DateTime objects can be compared using comparison operators.

$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2); // bool(false)
var_dump($date1 < $date2); // bool(true)
var_dump($date1 > $date2); // bool(false)