Skip to content
PHP Logo

How can the DateInterval function in PHP be used to calculate the difference in days between two dates?

To calculate the difference in days between two dates using the DateInterval function in PHP, you can create two DateTime objects representing the two dates, then calculate the difference between them using the diff() method. This will return a DateInterval object which can then be used to extract the number of days.

php
$date1 = new DateTime('2022-01-01');
$date2 = new DateTime('2022-01-10');

$interval = $date1->diff($date2);
echo $interval->days; // Output: 9