Calculate difference between two dates in PHP
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).
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $start_date = new DateTime("2015-10-31"); $end_date = new DateTime("2017-12-25"); $interval = $start_date->diff($end_date); echo $interval->format('%R%a days'); /* Output: +786 days */ ?> |
Alternatively, you can extract the number of years, months, and days information from the DateInterval object using its y, m, and d properties, respectively.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $start_date = new DateTime("2015-10-31"); $end_date = new DateTime("2017-12-25"); $interval = $start_date->diff($end_date); echo "$interval->y years, $interval->m months, $interval->d days"; /* Output: 2 years, 1 months, 25 days */ ?> |
Here’s a procedural version of the above code using date_diff(), which is an alias of DateTime::diff().
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $start_date = "2015-10-31"; $end_date = "2017-12-25"; $interval = date_diff(date_create($start_date), date_create($end_date)); echo "$interval->y years, $interval->m months, $interval->d days"; /* Output: 2 years, 1 months, 25 days */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $start_date = strtotime("2015-10-31"); $end_date = strtotime("2017-12-25"); $diff_in_days = floor(($end_date - $start_date) / (60 * 60 * 24)); echo $diff_in_days . ' days'; /* Output: 786 days */ ?> |
If you need to calculate the difference between the current date and another date, do the following:
|
1 2 3 4 5 6 7 |
<?php $now = time(); $date = strtotime("2025-12-25"); $diff_in_days = floor(($date - $now) / (60 * 60 * 24)); echo $diff_in_days . ' days'; ?> |
That’s all there is to calculating the day difference between two dates in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)