Find amount of days between 2 dates in php

后端 未结 2 1359
忘掉有多难
忘掉有多难 2020-12-22 08:46

I have 2 dates and want to know how many the amount of days that come between them.

Lets say these two are the dates

2015-11-16 10:01:13

相关标签:
2条回答
  • 2020-12-22 09:03

    Following my comment, I thought I would post some examples from the PHP.net manual:

    OOP style:

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

    Procedural style:

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

    Both examples will output:

    +2 days

    You can also compare word strings as such (when using OOP style, this is an example from PHP.net):

    <?php
    $date1 = new DateTime("now");
    $date2 = new DateTime("tomorrow");
    var_dump($date1 == $date2);
    var_dump($date1 < $date2);
    var_dump($date1 > $date2);
    ?>
    

    Producing:

    bool(false)
    bool(true)
    bool(false)

    Using your dates:

    OOP

    <?php
    $datetime1 = new DateTime('2015-11-16 10:01:13');
    $datetime2 = new DateTime('2015-05-06 09:47:16');
    $interval = $datetime1->diff($datetime2);
    echo $interval->format('%R%a days');
    ?>
    

    Procedural

    <?php
    $datetime1 = date_create('2015-11-16 10:01:13');
    $datetime2 = date_create('2015-05-06 09:47:16');
    $interval = date_diff($datetime1, $datetime2);
    echo $interval->format('%R%a days');
    ?>
    

    Result from both:

    -194 days

    I sincerely hope this helps :)

    0 讨论(0)
  • 2020-12-22 09:05

    Try this. It is very simple.

        <?php
    
         $date1 = strtotime("2015-11-16 10:01:13");
         $date2 = strtotime("2015-05-06 09:47:16");
         $datediff = $date1 - $date2;
         echo floor($datediff/(60*60*24))." days"; //output 194 days
    
        ?>
    
    0 讨论(0)
提交回复
热议问题