Countdown to a time
By: Daniel

If you have a date in the future that you want to show how many days, minutes, or seconds it is until that date, this is the script for you. When you provide a date in the future, it will return these values. If the time is alreay past, it shows “The countdown is over!”.

<?php
function timeLeft($theTime) {
  $now = strtotime("now");
  $timeLeft = $theTime - $now;
  
  if($timeLeft > 0) {
    $days = floor($timeLeft/60/60/24);
    $hours = $timeLeft/60/60%24;
    $mins = $timeLeft/60%60;
    $secs = $timeLeft%60;
    
    if($days) {
      $theText = $days . " Day(s)";
      if($hours) {
        $theText .= ", " .$hours . " Hour(s) ";
      }
    } elseif($hours) {
      $theText = $hours . " Hour(s)";
      if($mins) {
        $theText .= ", " .$mins . " Minute(s) ";
      }
    } elseif($mins) {
      $theText = $mins . " Minute(s)";
      if($secs) {
        $theText .= ", " .$secs . " Second(s) ";
      }
    } elseif($secs) {
      $theText = $secs . " Second(s)";
    }
  } else {
    $theText = "The countdown is over!";
  }

  return $theText;
}
?>

This function uses simple math to calculate these values and manipulates them to give you the display.

Here is an example usage for the code:

<?php
$testTime = strtotime("next Friday");
echo timeLeft($testTime).'<br>';

$testTime = strtotime("+1 year 1 month 1 week 1 days 1 hours 1 seconds");
echo timeLeft($testTime).'<br>';

$testTime = mktime(0, 0, 0, date("m")+1, date("d"), date("y"));
echo timeLeft($testTime);
?>
1 Star2 Stars3 Stars4 Stars5 Stars (8 votes, average: 4.38 out of 5)
Loading ... Loading ...

2 Responses to “Countdown to a time”

  1. codedone Says:

    Just what I was looking for :)

  2. achmad Says:

    good script, i want to try this’s script

Leave a Reply

geovisitors