dongpi3237 2018-02-28 02:58
浏览 33
已采纳

if if语句为PHP DateTime diff

I am using meta_box value (YmdHi) and current Date&time to print time difference. And this code work for me.

Now additionally i want to print Live when 2 hours left to start Event.

What mistake I 'm doing to print if or else currently this not work for me?

$then = date( get_post_meta( get_the_ID(), '_start_eventtimestamp', true ) ) ;
$then = new DateTime($then);
$now = new DateTime();
$sinceThen = $then->diff($now);

if ($sinceThen > 2 * HOUR_IN_SECONDS){
       echo $sinceThen->d.'days'; 
       echo $sinceThen->h.'hours'; 
       echo $sinceThen->i.'minutes';
 }
else{
        echo 'LIVE';
 }
  • 写回答

1条回答 默认 最新

  • drk7700 2018-02-28 03:14
    关注

    $sinceThen is a DateInterval (that's what DateTime::diff() returns), so you're comparing a int with an object, which obviously gives you unexpected results. To get the difference in seconds, subtract both DateTime instances' timestamps (which you obtain with DateTime::getTimestamp()):

    $then = date( get_post_meta( get_the_ID(), '_start_eventtimestamp', true ) ) ;
    $then = new DateTime($then);
    $now = new DateTime();
    $sinceThen = $then->diff($now);
    $sinceThenInSeconds = $then->getTimestamp() - $now->getTimestamp();
    
    if ($sinceThenInSeconds > 2 * HOUR_IN_SECONDS){
        echo $sinceThen->d.'days'; 
        echo $sinceThen->h.'hours'; 
        echo $sinceThen->i.'minutes';
    }
    else{
        echo 'LIVE';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?