控制剩余时间的输出

时间:2012-06-05 12:49:42

标签: php mysql html

我正在尝试添加一些php,显示我网站上的产品剩余时间,有点像拍卖。这一切都显示得很好但是当时间变得更低时显示0d 34h 12m这意味着0天,34小时和12分钟,我想知道如果没有剩下的日子,是否有办法摆脱0d位有点像这个34h 12m,它只是让它看起来更好,同样适用于没有剩余时间和几分钟的时间。

以下是计算剩余时间的代码

$date = date('m/d/Y h:i:s', time());
$date3 = new DateTime($date);
$date4 = new DateTime($time_ending);
$interval_date = $date3->diff($date4);
$time_left = $interval_date->d."d ". $interval_date->h."h ". $interval_date->i."m "; 

无论如何我能做到吗?

感谢您的帮助

4 个答案:

答案 0 :(得分:2)

是的,最短的方式是

$time_left = (($interval_date->d) ? $interval_date->d.'d ' : '')
           . (($interval_date->h) ? $interval_date->h.'h ' : '')
           . $interval_date->i.'m ';

简要解释(cond) ? (stmA) : (stmB)
等于if(cond){ stmA } else{ stmB }

答案 1 :(得分:1)

您可以使用此功能,请参阅:

function BetterLook($time, $sulfix)
{
    if ($time > 0)
    {
        return "$time $sulfix";
    }

    return "";
}

因此...

$time_left = BetterLook($interval_date->d, "d "). BetterLook($interval_date->h, "h "). BetterLook($interval_date->i, "m ");

答案 2 :(得分:0)

刚写下来,未经过测试。

$d = $interval_date->d;
$h = $interval_date->h;
$m = $interval_date->i; 

$time_left = ($d ? $d."d " : "") . ($d or $h ? $h."h " : "") . $i."m ";

更长,也许更容易阅读版本:

$time_left = "";

if($d) {
    $time_left .= $d . "d ";
}

if($d or $h) {
    $time_left .= $h . "h ";
}

$time_left .= $m . "m ";

答案 3 :(得分:0)

您是否尝试过简单的if语句来查看$interval_date->d是否小于1?如果是这样,那么只显示剩余时间。您可以在每个细分中执行此操作这不是测试,只是一个建议。

相关问题