Question

I'm creating a countdown for how long people can do specific functions on a specific page. I've made a countdown, but he is going under 0, so he's counting further negatively.

I'm printing out the countdown like this:

-4 days -10 h -3 m -34 s remaining to run 1210 meter

My countdown,

$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>
Was it helpful?

Solution

If you use DateTime() you can compare the two times and see if the stop time is in the past. If it is, display a different message. Also, this makes getting the interval between the two easier to get and display:

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

Keep in mind if you don't want to display zero values for time units it will be a little more complex:

$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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top