Finding the number of days between two dates

后端 未结 30 2466
心在旅途
心在旅途 2020-11-21 23:47

How to find number of days between two dates using PHP?

相关标签:
30条回答
  • 2020-11-22 00:17

    Easy to using date_diff

    $from=date_create(date('Y-m-d'));
    $to=date_create("2013-03-15");
    $diff=date_diff($to,$from);
    print_r($diff);
    echo $diff->format('%R%a days');
    
    • See more at: http://blog.innovsystems.com/php/get-number-days-between-two-dates-php
    0 讨论(0)
  • 2020-11-22 00:18

    Object oriented style:

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

    Procedural style:

    $datetime1 = date_create('2009-10-11');
    $datetime2 = date_create('2009-10-13');
    $interval = date_diff($datetime1, $datetime2);
    echo $interval->format('%R%a days');
    
    0 讨论(0)
  • 2020-11-22 00:18

    If you want to echo all days between the start and end date, I came up with this :

    $startdatum = $_POST['start']; // starting date
    $einddatum = $_POST['eind']; // end date
    
    $now = strtotime($startdatum);
    $your_date = strtotime($einddatum);
    $datediff = $your_date - $now;
    $number = floor($datediff/(60*60*24));
    
    for($i=0;$i <= $number; $i++)
    {
        echo date('d-m-Y' ,strtotime("+".$i." day"))."<br>";
    }
    
    0 讨论(0)
  • 2020-11-22 00:19

    Well, the selected answer is not the most correct one because it will fail outside UTC. Depending on the timezone (list) there could be time adjustments creating days "without" 24 hours, and this will make the calculation (60*60*24) fail.

    Here it is an example of it:

    date_default_timezone_set('europe/lisbon');
    $time1 = strtotime('2016-03-27');
    $time2 = strtotime('2016-03-29');
    echo floor( ($time2-$time1) /(60*60*24));
     ^-- the output will be **1**
    

    So the correct solution will be using DateTime

    date_default_timezone_set('europe/lisbon');
    $date1 = new DateTime("2016-03-27");
    $date2 = new DateTime("2016-03-29");
    
    echo $date2->diff($date1)->format("%a");
     ^-- the output will be **2**
    
    0 讨论(0)
  • 2020-11-22 00:19
    function howManyDays($startDate,$endDate) {
    
        $date1  = strtotime($startDate." 0:00:00");
        $date2  = strtotime($endDate." 23:59:59");
        $res    =  (int)(($date2-$date1)/86400);        
    
    return $res;
    } 
    
    0 讨论(0)
  • 2020-11-22 00:22

    I'm using Carbon in my composer projects for this and similar purposes.

    It'd be as easy as this:

    $dt = Carbon::parse('2010-01-01');
    echo $dt->diffInDays(Carbon::now());
    
    0 讨论(0)
提交回复
热议问题