PHP Date Time- Get difference in days between two dates

In this post we will be creating a PHP script that will calculate the difference in days between two given dates. To do this we will be using the date time ‘diff()’ function which returns the difference between two date time objects.

See below where we declare our two date time objects.

$date1 = new DateTime("2021-11-14");
$date2 = new DateTime("2022-09-26");

In the snippet of code below we use the ‘diff()’ function to get the difference and return this in days.

<?php
$date1 = new DateTime("2021-11-14");
$date2 = new DateTime("2022-09-26");
$difference = $date1->diff($date2);
echo($difference->days);
?>

The above would return the following as output.

316

Leave a Reply