Introduction:
PHP’s DateTime
class and the diff()
method can calculate the difference between two dates in various units.
Example:
<?php
$date1 = new DateTime("2024-01-01");
$date2 = new DateTime("2024-12-31");
$interval = $date1->diff($date2);
echo "Difference: " . $interval->days . " days";
?>
Explanation:
new DateTime()
creates date objects.diff()
computes the difference between two dates and returns aDateInterval
object.$interval->days
gives the total difference in days.