How to calculate the difference between two dates using PHP?

Spread the love

Sometimes, we want to calculate the difference between two dates using PHP.

In this article, we’ll look at how to calculate the difference between two dates using PHP.

How to calculate the difference between two dates using PHP?

To calculate the difference between two dates using PHP, we can use the date’s diff method.

For instance, we write

$date1 = new DateTime("2021-03-24");
$date2 = new DateTime("2022-06-26");
$interval = $date1->diff($date2);
echo $interval->y;
echo $interval->m;
echo $interval->d;

to create 2 DateTime objects $date1 and $date2.

Then we call $date->diff with $date2 to find the difference between $date2 and $date1.

We get the year difference from $interval->y , the month difference from $interval->m and the day difference from $interval->d.

We can also compare dates directly with comparison operators.

For instance, we write

$date1 = new DateTime("2021-03-24");
$date2 = new DateTime("2022-06-26");

var_dump($date1 == $date2);
var_dump($date1 < $date2);
var_dump($date1 > $date2);

to compare the 2 dates.

Conclusion

To calculate the difference between two dates using PHP, we can use the date’s diff method.

Leave a Reply

Your email address will not be published. Required fields are marked *