Getting the difference between two dates in PHP isn’t as trivial as you may think. Actually, it’s much simpler when compared to other programming languages. In this article, we will explore how to get key differences between a pair of dates in months, days, or years.
The easiest and simplest form of calculating the difference is by using PHP’s native date_diff() function. This function is super-clean, allowing you to get the key differences between dates in just a couple of lines of code. date_diff() has various format accessors that provide detailed differences between dates such as the number of years, days, and more.
Let’s take the two following dates for the example ahead
Date 1: 2020-01-01 10:30:00
Date 2: 2020-09-22 15:30:00
Using date_diff to calculate the difference between dates
The date_diff() function takes two important parameters to get its engines going, the DateTime from and the DateTime to. These DateTime parameters must be of proper types which can be solved in a variety of forms. In the following example, the DateTime parameters will be created using the date_create() function. After the date_diff object is created, particular values can then be accessed from its public properties.
Let’s get to the code
// Date to calculate from // Date to calculate to $dateDifference = date_diff(date_create("2020-01-01 12:30:00"), date_create("2020-09-20 22:00:00")); echo "Difference In Years: " . $dateDifference->y . "<br />"; echo "Difference In Months: " . $dateDifference->m . "<br />"; echo "Difference In Days: " . $dateDifference->days . "<br />";
Difference In Years: 0 Difference In Months: 8 Difference In Days: 263
What the date_diff() function also has available to use is a format function that can be passed any string with additional parameters to print out the date differences required. The format parameters can be viewed on the DateTime Interval matrix here.
Let’s see an example using the format function from date_diff()
$dateDifference = date_diff(date_create("2020-01-01 12:30:00"), date_create("2020-09-20 22:00:00"));echo $dateDifference->format('The difference in days between these two dates is %a');
The difference in days between these two dates is 263
I hope this versatile function helps you with your date calculations, as you can see for yourself, not only can you use a powerful format function to print key differences. But also you gain access to an array of properties to print values too. You can see the documentation for date_diff() here. And again, if you want to use the format() function, it is worth having a look at the following documentation DateTime Interval.