Calculate the number of days between two dates in PHP

In this article we will explain how to calculate the number of days between two dates in PHP. There are many different way to find the number of days between two dates in PHP.

Calculate the number of days between two dates in PHP

Method 1#

First we will convert start date and end date into to unix timestamps using strtotime() function, then substract end date to start date then it will give you the difference in seconds, which you divide by 86400 (total seconds in a day) to give you an approximate total of days in that range.

<?php
function dateDifference($start_date, $end_date)
{
    // calulating the difference in timestamps 
    $diff = strtotime($start_date) - strtotime($end_date);
     
    // 1 day = 24 hours 
    // 24 * 60 * 60 = 86400 seconds
    return ceil(abs($diff / 86400));
}
 
// start date 
$start_date = "2016-01-02";
 
// end date 
$end_date = "2016-01-21";
 
// call dateDifference() function to find the number of days between two dates
$dateDiff = dateDifference($start_date, $end_date);
 
echo "Difference between two dates: " . $dateDiff . " Days ";
?> 

The above example will output:

Difference between two dates: 19 Days

Three PHP functions are used in the above script to find the number of days between two dates.

The strtotime() function is a built-in function in PHP which is used to convert an English textual date-time description to a UNIX timestamp.
The abs() function returns the absolute (positive) value of a number.
The ceil() function is used to round a number to the nearest greater integer.

Method 2# DateTime::diff()

<?php
$start_date = date_create("2016-01-02");
$end_date   = date_create("2016-01-21");

//difference between two dates
$diff = date_diff($start_date,$end_date);

//find the number of days between two dates
echo "Difference between two dates: ".$diff->format("%a"). " Days ";
?>

The above example will output:

Difference between two dates: 19 Days

Method 3# DateTime::diff()

<?php
$start_date = new DateTime('2016-01-02');
$end_date = new DateTime('2016-01-21');

//difference between two dates
$diff = $start_date->diff($end_date);

//find the number of days between two dates
echo "Difference between two dates: ".$diff->format("%a"). " Days ";
?>

The above example will output:

Difference between two dates: 19 Days

In the above Method 2#, Method 3# used date_diff() function returns the difference between two DateTime objects.

I hope you like this Post, Please send me any comment, suggestion or correction you may have – we are here to solve your problems. Thanks

Leave A Reply

Your email address will not be published.