How to calculate the difference between two dates in PHP?

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 a DateInterval object.
  • $interval->days gives the total difference in days.

Leave a Reply

Your email address will not be published. Required fields are marked *