I am using PHP as server side language to display a countdown. It does work well (keeping in ming the limitation of server side countdowns) but it goes to a negative countdown once the date has expired.
For example:
<?php
date_default_timezone_set('Europe/London');
$date = strtotime("November 22, 2017 12:01 AM");
$remaining = $date - time();
$days_remaining = floor($remaining / 86400);
$hours_remaining = floor(($remaining % 86400) / 3600);
$minutes_remaining = floor(($remaining % 3600) / 60);
?>
Once the November 22 is finished the countdown will output negative values. Can you please help me with how to hide the countdown once the $date
has expired?
I am outputting the result using the below code:
<?php echo $days_remaining?> : <?php echo $hours_remaining?> : <?php echo $minutes_remaining?>
Add a simple check for positivity of the $remaining
value using if statement:
date_default_timezone_set('Europe/London');
$date = strtotime("November 22, 2017 12:01 AM");
$remaining = $date - time();
if ($remaining > 0) {
$days_remaining = floor($remaining / 86400);
$hours_remaining = floor(($remaining % 86400) / 3600);
$minutes_remaining = floor(($remaining % 3600) / 60);
}
In output file:
<? if ($remaining > 0) { ?>
<?= $days_remaining ?> : <?= $hours_remaining ?> : <?= $minutes_remaining ?>
<? } ?>
It's more readable to use the syntax <?= $var ?>
to output something in PHP (option short_open_tag must have On
value in php.ini
).