How do I compare two DateTime objects in PHP 5.2.8?

后端 未结 7 1934
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 17:42

Having a look on the PHP documentation, the following two methods of the DateTime object would both seem to solve my problem:

  • DateTime::diff : Get
相关标签:
7条回答
  • 2020-11-22 17:44

    If you want to compare dates and not time, you could use this:

    $d1->format("Y-m-d") == $d2->format("Y-m-d")
    
    0 讨论(0)
  • 2020-11-22 17:47
    $elapsed = '2592000';
    // Time in the past
    $time_past = '2014-07-16 11:35:33';
    $time_past = strtotime($time_past);
    
    // Add a month to that time
    $time_past = $time_past + $elapsed;
    
    // Time NOW
    $time_now = time();
    
    // Check if its been a month since time past
    if($time_past > $time_now){
        echo 'Hasnt been a month';    
    }else{
        echo 'Been longer than a month';
    }
    
    0 讨论(0)
  • 2020-11-22 17:49

    The following seems to confirm that there are comparison operators for the DateTime class:

    dev:~# php
    <?php
    date_default_timezone_set('Europe/London');
    
    $d1 = new DateTime('2008-08-03 14:52:10');
    $d2 = new DateTime('2008-01-03 11:11:10');
    var_dump($d1 == $d2);
    var_dump($d1 > $d2);
    var_dump($d1 < $d2);
    ?>
    bool(false)
    bool(true)
    bool(false)
    dev:~# php -v
    PHP 5.2.6-1+lenny3 with Suhosin-Patch 0.9.6.2 (cli) (built: Apr 26 2009 20:09:03)
    Copyright (c) 1997-2008 The PHP Group
    Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
    dev:~#
    
    0 讨论(0)
  • 2020-11-22 17:54

    You can also compare epoch seconds :

    $d1->format('U') < $d2->format('U')
    

    Source : http://laughingmeme.org/2007/02/27/looking-at-php5s-datetime-and-datetimezone/ (quite interesting article about DateTime)

    0 讨论(0)
  • 2020-11-22 17:55

    From the official documentation:

    As of PHP 5.2.2, DateTime objects can be compared using comparison operators.

    $date1 = new DateTime("now");
    $date2 = new DateTime("tomorrow");
    
    var_dump($date1 == $date2); // false
    var_dump($date1 < $date2); // true
    var_dump($date1 > $date2); // false
    

    For PHP versions before 5.2.2 (actually for any version), you can use diff.

    $datetime1 = new DateTime('2009-10-11'); // 11 October 2013
    $datetime2 = new DateTime('2009-10-13'); // 13 October 2013
    
    $interval = $datetime1->diff($datetime2);
    echo $interval->format('%R%a days'); // +2 days
    
    0 讨论(0)
  • 2020-11-22 17:57

    As of PHP 7.x, you can use the following:

    $aDate = new \DateTime('@'.(time()));
    $bDate = new \DateTime('@'.(time() - 3600));
    
    $aDate <=> $bDate; // => 1, `$aDate` is newer than `$bDate`
    
    0 讨论(0)
提交回复
热议问题