This article demonstrates how to calculate the day difference between two dates in PHP.

1. Using DateTime::diff() function

The recommended solution to calculate the number of days between two dates is to convert both dates into DateTime objects and use the DateTime::diff() function to get the DateInterval object representing their difference. Then you may use the DateInterval::format() function with the formatting option '%a', indicating the absolute number of days. Consider appending the '%R' prefix ('%R%a') to get it as a signed integer ('-' when negative, '+' when positive).

Download  Run Code

 
Alternatively, you can extract the number of years, months, and days information from the DateInterval object using its y, m, and d properties, respectively.

Download  Run Code

 
Here’s a procedural version of the above code using date_diff(), which is an alias of DateTime::diff().

Download  Run Code

2. Using strtotime() function

You can get the number of seconds between the two dates by converting each date to a Unix timestamp and calculating the difference between the two. Then you can convert the difference in seconds into the number of days. This can be easily done using the strtotime() function, which converts the date string into a Unix timestamp. Note that the PHP documentation for the strtotime()` function advises not to use it for mathematical operations.

Download  Run Code

 
If you need to calculate the difference between the current date and another date, do the following:

Download  Run Code

That’s all there is to calculating the day difference between two dates in PHP.