Calculating The Difference Between Two Dates in PHP

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 />";