Find Number of Days Between Two Dates
The diff() function in PHP calculates the difference between two dates. It accepts two `DateTime` objects or date strings as arguments, returning a `DateInterval` object that provides the difference in years, months, days, and other intervals.
Example
<?php $date1 = new DateTime("2023-05-01"); $date2 = new DateTime("2024-12-24"); $interval = $date1->diff($date2); echo "Difference: " . $interval->y . " years, " . $interval->m . " months, " . $interval->d . " days\n"; echo "Total days difference: " . $interval->days; ?>
Output
Difference: 1 years, 7 months, 23 days Total days difference: 603
Here is an example to find the date and time difference between two date.
Example
<?php $date1 = new DateTime("2023-07-06 14:30:00"); $date2 = new DateTime("2024-12-24 18:45:30"); $interval = $date1->diff($date2); echo "Difference: " . $interval->y . " years, " . $interval->m . " months, " . $interval->d . " days, " . $interval->h . " hours, " . $interval->i . " minutes, " . $interval->s . " seconds "; echo "\nTotal days difference: " . $interval->days; ?>
Output
Difference: 1 years, 5 months, 18 days, 4 hours, 15 minutes, 30 seconds