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';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥15 小红薯封设备能解决的来
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'
  • ¥15 vue+element项目中多tag时,切换Tab时iframe套第三方html页面需要实现不刷新
  • ¥50 深度强化学习解决能源调度问题
  • ¥15 一道计算机组成原理问题