如何在计时器上检查时间是否到了


How to check if time is up in timer?

我正在创建一个倒计时,显示人们在特定页面上执行特定功能的时间。我做了一个倒计时,但是他在0以下,所以他继续负计数。

我像这样打印出倒计时:

<>之前-4天-10小时-3米-34秒剩余1210米之前

我的倒计时,

$Date = "" . $groups['group_date'] . "";
$stopDate = date('Y-m-d H:i:s', strtotime($Date. ' +' . $periodOfRunning . 'days'));
   <h3><?php    $rem = strtotime($stopDate) - time();
    $day = floor($rem / 86400);
    $hr  = floor(($rem % 86400) / 3600);
    $min = floor(($rem % 3600) / 60);
    $sec = ($rem % 60);
    if($day) echo "$day days ";
    if($hr) echo "$hr h ";
    if($min) echo "$min m ";
    if($sec) echo "$sec s";
    echo " remaining to run " . $totalDistanceToDo . " meter";
            ?></h3>

如果您使用DateTime(),您可以比较这两个时间,看看停止时间是否在过去。如果是,则显示不同的消息。此外,这使得获取两者之间的间隔更容易获取和显示:

$now = new DateTime();
$stopdate = new DateTime($stopDate);
if ($stopdate > $now) {
    $diff = $now->diff($stopTime);
    echo $diff->format('%d days, %h hours, %i minutes, %s seconds');
    echo " remaining to run " . $totalDistanceToDo . " meter";
}
else {
    // negative time. display something else
}

请记住,如果你不想在时间单位中显示零值,它将稍微复杂一点:

$now = new DateTime();
$stopdate = new DateTime($stopDate);
if ($stopdate > $now) {
    $diff = $now->diff($stopTime);
    if ($diff->d > 0) echo $diff->d . ' days, ';
    if ($diff->h > 0) echo $diff->h . ' hours, ';
    if ($diff->i > 0) echo $diff->i . ' minutes, ';
    if ($diff->s > 0) echo $diff->s . ' seconds';
    echo " remaining to run " . $totalDistanceToDo . " meter";
}
else {
    // negative time. display something else
}