PHP

How to calculate the difference between two dates in PHP

April 1, 2022

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 and in an easy and practical way, so that you have no more doubts about it.

calculate the difference between two dates cover

Hey you programmer, ok? Let’s learn more about PHP and date calculation!

A very interesting and efficient way to make the difference between two dates is using the DateTime library

The advantage is that it is already object-oriented, so it is very easy to use.

Basically we must instantiate two objects with the dates that will have their difference calculated

And use the diff method, from the first to the second, for example

See it in action:

<?php
 $d1 = new DateTime('now');
 $d2 = new DateTime('1991-02-05');
 
 $interval = $d1->diff( $d2 );

 echo "Difference of " . $interval->d . " days";
 echo " and " . $interval->m . " months";
 echo " and " . $intervalo->y . " years.";

Notice that we can redeem the days with the property d, the months with the m and the years with the property y

The return will be:

Difference of x days and x months and x years.

Now you can calculate the differences between two dates in a simple way with PHP! 😀

Conclusion

In this article we learned  how to calculate the difference between two dates in PHP

We use the DateTime class, which offers us the possibility to run the calculation with an object-oriented interface

We simply instantiate the two dates and apply the diff method

Do you want to learn more about PHP and web development? If yes, click here! 🙂

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x