How to Calculate the Difference between Two Dates Using PHP?

This snippet will explain how to calculate the difference between two dates in PHP. Here, we provide you with information on how to do it accurately.

Watch a course Learn object oriented PHP

The simplest and most efficient ways to meet that goal is using the DateTime and DateInterval objects like this:

<?php

$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m . " months, " . $interval->d . " days "; 
// displays the total amount of days (not divided into years, months, and days) 
echo "difference " . $interval->days . " days ";

?>

Starting from PHP 5.2.2., you can compare DateTime objects with the help of comparison operators.

Here is an example:

<?php

$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)

?>

Describing DateTime and DateInterval in PHP

The manipulation of date and time is an inevitable part of programming. To be able to work with data and time, one should be aware of the arsenal of the PHP tools.

In this snippet, we represented to you how to calculate the difference between two dates the help of DateTime and DateInterval.

DateTime objects are considered comparable.

A DateInterval is capable of storing either a fixed amount of time( in hours, days, months, or years) or in a relative time string with the format, which is supported by DateTime.