How to calculate the difference between two dates in PHP

How to calculate the difference between two dates in PHP

In this article we will learn how to calculate the difference between two dates in PHP.

To calculate the difference between two dates in PHP, you can use the DateTime class along with the diff() method. Here’s an example:

$date1 = new DateTime('2021-01-01');
$date2 = new DateTime('2023-07-07');

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

// Access the difference in various units
$years = $interval->y;
$months = $interval->m;
$days = $interval->d;
$totalDays = $interval->days;

echo "Difference: $years years, $months months, $days days <br>";
echo "Total Difference in Days: $totalDays";

Output :

Difference: 2 years, 6 months, 6 days
Total Difference in Days: 917

In this example, we create two DateTime objects representing the two dates you want to calculate the difference between ($date1 and $date2).

We then use the diff() method on $date1 and pass $date2 as an argument. This returns a DateInterval object, which contains the difference between the two dates.

You can access the difference in various units using the properties of the DateInterval object. For example, $interval->y gives the difference in years, $interval->m gives the difference in months, and $interval->d gives the difference in days.

The property $interval->days gives the total difference in days, which includes all the years, months, and remaining days.

You can customize the format of the output as per your requirements. The example above demonstrates how to access the difference in years, months, and days and display it.