Compare given date with today

前端 未结 13 2187
别那么骄傲
别那么骄傲 2020-11-22 16:22

I have following

$var = \"2010-01-21 00:00:00.0\"

I\'d like to compare this date against today\'s date (i.e. I\'d like to know if this

13条回答
  •  盖世英雄少女心
    2020-11-22 16:45

    You can use the DateTime class:

    $past   = new DateTime("2010-01-01 00:00:00");
    $now    = new DateTime();
    $future = new DateTime("2021-01-01 00:00:00");
    

    Comparison operators work*:

    var_dump($past   < $now);         // bool(true)
    var_dump($future < $now);         // bool(false)
    
    var_dump($now == $past);          // bool(false)
    var_dump($now == new DateTime()); // bool(true)
    var_dump($now == $future);        // bool(false)
    
    var_dump($past   > $now);         // bool(false)
    var_dump($future > $now);         // bool(true)
    

    It is also possible to grab the timestamp values from DateTime objects and compare them:

    var_dump($past  ->getTimestamp());                        // int(1262286000)
    var_dump($now   ->getTimestamp());                        // int(1431686228)
    var_dump($future->getTimestamp());                        // int(1577818800)
    var_dump($past  ->getTimestamp() < $now->getTimestamp()); // bool(true)
    var_dump($future->getTimestamp() > $now->getTimestamp()); // bool(true)
    

    * Note that === returns false when comparing two different DateTime objects even when they represent the same date.

提交回复
热议问题