【问题标题】:If else statement for PHP DateTime diffPHP DateTime diff 的 if else 语句
【发布时间】:2018-02-28 02:58:18
【问题描述】:

我正在使用 meta_box 值 (YmdHi)current Date&time 来打印时差。这段代码对我有用。

现在我还想在还有 2 小时开始活动时打印 Live

我在打印 if or else 时犯了什么错误,目前这对我不起作用?

$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';
 }

【问题讨论】:

    标签: php wordpress if-statement


    【解决方案1】:

    $sinceThenDateInterval(这就是 DateTime::diff() 返回的内容),因此您将 intobject 进行比较,这显然会给您带来意想不到的结果。要获得以秒为单位的差异,请减去两个 DateTime 实例的时间戳(通过 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';
    }
    

    【讨论】:

    • 现场打印到正确的地方,但现在日期和时间只有这个节目有问题(天小时分钟)
    • 对不起,忘了你还在用$sinceThen。我编辑了,现在试试!
    • 我怎样才能得到两位数的值?如果当前输出为2days2hours2min,则将其更改为02days02hours02min
    • @MuhammadArifKamboh 使用format()。在您的 if 块内,而不是那些 3 echos,粘贴这个 echo $sinceThen->format("%D days, %H hours and %M minutes");
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2011-05-18
    • 2015-06-21
    • 1970-01-01
    相关资源
    最近更新 更多