[php] How to count days between two dates in PHP?

If I have a couple of strings $startDate and $endDate which are set to (for instance) "2011/07/01" and "2011/07/17" (meaning 1 July 2011 and 17 July 2011). How would I count the days from start date to end date? In the example given, it would be 17 days.

This question is related to php date count

The answer is


None of the solutions worked for me. For those who are still on PHP 5.2 (DateTime::diff was introduced in 5.3), this solution works:

function howDays($from, $to) {
    $first_date = strtotime($from);
    $second_date = strtotime($to);
    $offset = $second_date-$first_date; 
    return floor($offset/60/60/24);
}

$date1 = date_create("2017-04-15");
$date2 = date_create("2017-05-18");

//difference between two dates
$diff = date_diff($date1,$date2);

//count days
echo 'Days Count - '.$diff->format("%a");

In case your DateTime has also hour:minutes:seconds and you still want to have the number of days..

   /**
     * Returns the total number of days between to DateTimes, 
     * if it is within the same year
     * @param $start
     * @param $end
     */
    public function dateTimesToDays($start,$end){
       return intval($end->format('z')) - intval($start->format('z')) + 1;
    }

https://github.com/dukeatcoding/timespan-converter


You can use date_diff to calculate the difference between two dates:

$date1 = date_create("2013-03-15");
$date2 = date_create("2013-12-12");
$diff =  date_diff($date1 , $date2);
echo  $diff->format("%R%a days");

i created a function in which if you pass two dates than it will return day wise value. For better understanding please see the output of start date : 2018-11-12 11:41:19 and End Date 2018-11-16 12:07:26

private function getTimeData($str1,$str2){
$datetime1 = strtotime($str1);
$datetime2 = strtotime($str2);
$myArray = array();
if(date('d', $datetime2) != date('d', $datetime1) ||  date('m', $datetime2) != date('m', $datetime1) || date('y', $datetime2) != date('y', $datetime1)){
    $exStr1 = explode(' ',$str1);
    $exStr2 = explode(' ',$str2);
    $datediff = strtotime($exStr2[0]) - strtotime($exStr1[0]);
    $totalDays = round($datediff / (60 * 60 * 24));
    $actualDate1 = $datetime1;
    $actualDate2 = date('Y-m-d', $datetime1)." 23:59:59";
    $interval  = abs(strtotime($actualDate2)-$actualDate1);
    $minutes   = round($interval / 60);
    $myArray[0]['startDate'] = date('Y-m-d H:i:s', $actualDate1); 
    $myArray[0]['endDate'] = $actualDate2;
    $myArray[0]['minutes'] = $minutes;
    $i = 1;
    if($totalDays > 1){    
        for($i=1; $i<$totalDays; $i++){
            $dayString = "+".$i." day";
            $edate = strtotime($dayString, $actualDate1);
            $myArray[$i]['startDate'] = date('Y-m-d', $edate)." 00:00:00"; 
            $myArray[$i]['endDate'] = date('Y-m-d', $edate)." 23:59:59"; 
            $myArray[$i]['minutes'] = 1440;
        }
    }
    $actualSecDate1 = date('Y-m-d', $datetime2)." 00:00:00";
    $actualSecDate2 = $datetime2;
    $interval  = abs(strtotime($actualSecDate1)-$actualSecDate2);
    $minutes   = round($interval / 60);
    $myArray[$i]['startDate'] = $actualSecDate1; 
    $myArray[$i]['endDate'] = date('Y-m-d H:i:s', $actualSecDate2); 
    $myArray[$i]['minutes'] = $minutes;
}
else{
    $interval  = abs($datetime2-$datetime1);
    $minutes   = round($interval / 60);
    $myArray[0]['startDate'] = date('Y-m-d H:i:s', $datetime1); 
    $myArray[0]['endDate'] = date('Y-m-d H:i:s', $datetime2);
    $myArray[0]['minutes'] = $minutes;
}

return $myArray;
}

Output

Array
(
[0] => Array
    (
        [startDate] => 2018-11-12 11:41:19
        [endDate] => 2018-11-12 23:59:59
        [minutes] => 739
    )

[1] => Array
    (
        [startDate] => 2018-11-13 00:00:00
        [endDate] => 2018-11-13 23:59:59
        [minutes] => 1440
    )

[2] => Array
    (
        [startDate] => 2018-11-14 00:00:00
        [endDate] => 2018-11-14 23:59:59
        [minutes] => 1440
    )

[3] => Array
    (
        [startDate] => 2018-11-15 00:00:00
        [endDate] => 2018-11-15 23:59:59
        [minutes] => 1440
    )

[4] => Array
    (
        [startDate] => 2018-11-16 00:00:00
        [endDate] => 2018-11-16 12:07:26
        [minutes] => 727
    )
)

If you want to know the number of days (if any), the number of hours (if any), minutues (if any) and seconds, you can do the following:

$previousTimeStamp = strtotime("2011/07/01 21:12:34");
$lastTimeStamp = strtotime("2013/09/17 12:34:11");

$menos=$lastTimeStamp-$previousTimeStamp;

$mins=$menos/60;
if($mins<1){
$showing= $menos . " seconds ago";
}
else{
$minsfinal=floor($mins);
$secondsfinal=$menos-($minsfinal*60);
$hours=$minsfinal/60;
if($hours<1){
$showing= $minsfinal . " minutes and " . $secondsfinal. " seconds ago";

}
else{
$hoursfinal=floor($hours);
$minssuperfinal=$minsfinal-($hoursfinal*60);
$days=$hoursfinal/24;
if($days<1){
$showing= $hoursfinal . "hours, " . $minssuperfinal . " minutes and " . $secondsfinal. " seconds ago";

}
else{
$daysfinal=floor($days);
$hourssuperfinal=$hoursfinal-($daysfinal*24);
$showing= $daysfinal. "days, " .$hourssuperfinal . " hours, " . $minssuperfinal . " minutes and " . $secondsfinal. " seconds ago";
}}}

echo $showing;

You could use the same logic if you want to add months and years.


<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

Source: http://www.php.net/manual/en/datetime.diff.php


PHP has a date_diff() function to do this.


Use DateTime::diff (aka date_diff):

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);

Or:

$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);

You can then get the interval as a integer by calling $interval->days.


Simple way to count is,

$currentdate = date('Y-m-d H:i:s');
$after1yrdate =  date("Y-m-d H:i:s", strtotime("+1 year", strtotime($data)));

$diff = (strtotime($after1yrdate) - strtotime($currentdate)) / (60 * 60 * 24);

echo "<p style='color:red'>The difference is ".round($diff)." Days</p>";

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to count

Count the Number of Tables in a SQL Server Database SQL count rows in a table How to count the occurrence of certain item in an ndarray? Laravel Eloquent - distinct() and count() not working properly together How to count items in JSON data Powershell: count members of a AD group How to count how many values per level in a given factor? Count number of rows by group using dplyr C++ - how to find the length of an integer JPA COUNT with composite primary key query not working