Are PHP DateInterval comparable like DateTime?

前端 未结 7 2074
孤城傲影
孤城傲影 2020-12-03 13:36

I discovered that a DateTime object in PHP can be compared to another as the \">\" and \"<\" operators are overloaded.

Is it the same with DateInterval?

A

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 14:05

    In short, comparing of DateInterval objects is not currently supported by default (as of php 5.6).

    As you already know, the DateTime Objects are comparable.

    A way to achieve the desired result, is to subtract or add the DateInterval from a DateTime object and compare the two to determine the difference.

    Example: https://3v4l.org/kjJPg

    $buildDate = new DateTime('2012-02-15');
    $releaseDate = clone $buildDate;
    $releaseDate->setDate(2012, 2, 14);
    $buildDate->add(new DateInterval('P15D'));
    
    var_dump($releaseDate < $buildDate); //bool(true)
    

    Edit

    As of the release of PHP 7.1 the results are different than with PHP 5.x, due to the added support for microseconds.

    Example: https://3v4l.org/rCigC

    $a = new \DateTime;
    $b = new \DateTime;
    
    var_dump($a < $b);
    

    Results (7.1+):

    bool(true)
    

    Results (5.x - 7.0.x, 7.1.3):

    bool(false)
    

    To circumvent this behavior, it is recommended that you use clone to compare the DateTime objects instead.

    Example: https://3v4l.org/CSpV8

    $a = new \DateTime;
    $b = clone $a;
    var_dump($a < $b);
    

    Results (5.x - 7.x):

    bool(false)
    

提交回复
热议问题