HTML Countdown to Date (Javascript Timer)

Description

  • The following Javascript generator will help you create a countdown clock that will count down the seconds, minutes, hours, days, weeks, years remaining until your target date.
  • This is the second version of this script. The "Display Settings" section was added. The AM/PM bug with creating dateFuture was fixed. The function GetCount() was changed to allow multiple countdowns on the same page.

Note

  • Display Settings
    • Disabled If the number is disabled, it will never be shown. Any amount that exists is passed on to smaller increments. (eg; 4 hours disabled will display as 240 mins instead)
    • Show 0-99+ The number is always shown (even if it is a zero)
    • Show 1-99+ The number is shown if its value is 1 or more (zero is hidden)
    • Show 00-99+ The number is always shown (even if it is a zero). A two-digit number is always shown (for 0-9)
    • Show 01-99+ The number is shown if its value is 1 or more (zero is hidden). A two-digit number is shown for 1-9
  • If you want to change the size, font, or color you can edit the last line of your generated code and add a style="" property like: <div id="countbox1" style="font:14pt Arial; color:#FF0000;"></div>
  • Enabling Milliseconds requires the browser to update the countdown about 40 times every second (when disabled it only runs/updates once per second). Enabling milliseconds uses WAY more processing power, although it shouldn't cause problems unless the computer or browser is very old.

Steps

  1. Fill in the required target Date and target Time information
  2. Fill in how you want your countdown to be displayed
  3. Generate the HTML and JavaScript code for your countdown (button at bottom)
  4. You can preview your script (button at bottom)
  5. Copy and Paste the Source Code into your HTML page


Date Expires
Year:
Month:
Day:
Time Expires
Hour:
Minute:
Second:


Display Settings
NOTE: the default display setting will work for most people
They only need to be changed if you want to customize what is shown
Show Years: Disabled
Show 0-99+
Show 1-99+
Show 00-99+
Show 01-99+
Wording:
singular
plural
Show Weeks: Disabled
Show 0-99+
Show 1-99+
Show 00-99+
Show 01-99+
Wording:
singular
plural
Show Days: Disabled
Show 0-99+
Show 1-99+
Show 00-99+
Show 01-99+
Wording:
singular
plural
Show Hours: Disabled
Show 0-23
Show 1-23
Show 00-23
Show 01-23
Wording:
singular
plural
Show Minutes: Disabled
Show 0-59
Show 1-59
Show 00-59
Show 01-59
Wording:
singular
plural
Show Seconds: Disabled
Show 0-59
Show 1-59
Show 00-59
Show 01-59
Wording:
singular
plural
Show Milliseconds: Disabled
Show .000-.999
 



Source Code:
Your countdown expires: (select Preview first)

Comments

This page contains the new version of the old v1 HTML Date with Countdown Timer. Using many of the old comments as guidelines, this new version was created that allows you to automatically make many of the requested customizations (instead of manually needing to edit the code).

I tested it fairly thoroughly, but you can report any bugs or glitches here.

To add custom labels on two countdowns, change:
document.getElementById(iid).innerHTML=out;to

if(iid=='countbox1'){
document.getElementById(iid).innerHTML="Sale ends in: "+out;
}
else if(iid=='countbox2'){
document.getElementById(iid).innerHTML="Expires in: "+out;
}

where the if() conditions match what you named the separate IDs

If you want to forward the user's browser to a new page once the countdown has expired, edit your code and change:
document.getElementById(iid).innerHTML="Now!";to:
window.location="index2.html";be aware it's not secure. Anyone would be able to get the new page by looking at the page source. Also, anyone who visits the page with the countdown expired would always get forwarded to index2.html

If you want to show a unique message if the countdown will expire today (less than 24hrs left) you can replace:

if(amount < 0){
document.getElementById(iid).innerHTML="Now!";
}
with:
if(amount < 0){
document.getElementById(iid).innerHTML="Past!";
}
else if(amount < 86400000){// if time remaining is less than one day (60s*60m*24h*1000ms)
document.getElementById(iid).innerHTML="Today!";
}

That will show "Today!" messages if less than 24hrs are left and "Past!" if the countdown has expired.

Thanks for your efforts on this - it is a useful piece of code. I'd like to base the countdown on the server's clock instead of the clock on the user's PC. Maybe this will be useful to others who would also like to do this.

I can do that by doing the date/time calculations on the server and sending the total seconds to this function (along with a few mods to pass the seconds to the amount variable and remove the division for milliseconds). The problem I'm having is that it will display the starting timer but will not advance. Do you see anything that would be causing this? Thanks.

It's a bit harder than it sounds. You'll need to use PHP to do all the initial calculations, then just use javascript to subtract how much time has elapsed since the browser was loaded. Change your dateFuture line like:

dateFuture1 = new Date(2011,3,20,15,31,46);

to:
<?php
   
//amount of server seconds until expires *1000 (to get ms)
   
echo "server_amount=". (mktime(15,31,46,4,20,2011) - time())*1000 .";\n";

// [edit: 2011-10-11] if you need a timezone specific time, base the expires off GMT and use gmmktime() instead. eg;
// echo "server_amount=". (gmmktime(5,0,0,12,20,2011) - time())*1000 .";\n";
?>

// now holds browser based expiration date as (milliseconds) int instead of JS date object
dateFuture1 = server_amount + new Date().getTime();

and the calculation line from:
amount = ddate.getTime() - dateNow.getTime();
to
// modified for int instead of JS date object
amount = ddate - dateNow.getTime();

You will need to use mktime() in PHP to create the expiration date. It does not use the same formatting as Javascript Date() does you'll need to manually convert your expires time (note: PHP also uses 1-12 months instead of 0-11 like Javascript).

Hello, using Perl I have captured the server time in local variables, what format do I change it to to make it compatible with your javascript?
Thanks.

If you're using code similar to the above, you need to create the unix timestamp for when the timer expires, subtract the current unix timestamp, then print the javascript server_amount variable with that value assigned to it. Probably something like:
print "server_amount="".(1342940482-time)."";\n";

Hi! This Javascript generator is a superb piece of work. :) I'm not an expert in Javascript, so please forgive me for asking: how do you merge two countdowns into a single script? I did your instructions by changing the values into dateFuture2 and countbox2, but only one countdown is appearing on my site.

It's unnecessary to have everything twice when you need two countdowns. You just need to double up those specific dateFuture2 and countbox2 parts.
<script type="text/javascript">
dateFuture1 = new Date(2011,8,19,10,00,00);
dateFuture2 = new Date(2011,10,3,9,00,00);


function GetCount(ddate,iid){

dateNow = new Date(); //grab current date
amount = ddate.getTime() - dateNow.getTime(); //calc milliseconds between dates
delete dateNow;

// if time is already past
if(amount < 0){
document.getElementById(iid).innerHTML="Now!";
}
// else date is still good
else{
days=0;hours=0;mins=0;secs=0;out="";

amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs

days=Math.floor(amount/86400);//days
amount=amount%86400;

hours=Math.floor(amount/3600);//hours
amount=amount%3600;

mins=Math.floor(amount/60);//minutes
amount=amount%60;

secs=Math.floor(amount);//seconds

if(days != 0){out += days +" "+((days==1)?"day":"days")+", ";}
if(hours != 0){out += hours +" "+((hours==1)?"hour":"hours")+", ";}
out += mins +" "+((mins==1)?"min":"mins")+", ";
out += secs +" "+((secs==1)?"sec":"secs")+", ";
out = out.substr(0,out.length-2);
document.getElementById(iid).innerHTML=out;

setTimeout(function(){GetCount(ddate,iid)}, 1000);
}
}

window.onload=function(){
GetCount(dateFuture1, 'countbox1');
GetCount(dateFuture2, 'countbox2');

};

</script>
<div id="countbox1"></div>
<div id="countbox2"></div>

Where is the generated remaining time linked to? Which time zone? My project today is to generate a countdown clock for September 8, 2011 at 8:30p ET. The result I get appears to be 21 hours later than a countdown clock which is adjusted from GMT to -4:00GMT for NYC (ET zone).

I get 74 days, 3 hours ... and the GMT adjusted site is running at 73 days, 6 hours. Is it possible to properly adjust for ET?

[edit] Thanks tons it is working perfectly now!

The countdown will show the time remaining until September 8, 2011 at 8:30pm in visitor's local time. It is not timezone specific.

To make it count down to in a specific timezone, near the top directly under your dateFuture1 line, add these new lines:

//set this to the number of hours offset from GMT
tzOffset = -4;

dx = dateFuture1.toGMTString();
dx = dx.substr(0,dx.length -3);
tzCurrent=(dateFuture1.getTimezoneOffset()/60)*-2;
dateFuture1.setTime(Date.parse(dx))
dateFuture1.setHours(dateFuture1.getHours() + tzCurrent - tzOffset);

make sure you change the tzOffset value to whatever your GMT timezone offset is. Also be aware daylight savings time can screw with it depending on where you live.

I found when adding a link to the output message that the quotes in the link are throwing off the rest. So I had to use:
document.getElementById(iid).innerHTML='Go to: <a href="#test">test</a> '+out;

I'm new to javascript, so I'm not sure whats the best way to achieve this - I'd like to have hours-days-seconds to have different classes or be in different divs. What would the best way to do this be?

the easiest way would be to edit the "out" string. Change (your code might look slightly different depending on the settings):

if(days != 0){out += days +" "+((days==1)?"day":"days")+", ";}
if(hours != 0){out += hours +" "+((hours==1)?"hour":"hours")+", ";}
out += mins +" "+((mins==1)?"min":"mins")+", ";
out += secs +" "+((secs==1)?"sec":"secs")+", ";
to something like
if(days != 0){out += '<div class="days">'+days +" "+((days==1)?"day":"days")+"</div>";}
if(hours != 0){out += '<div class="hours">'+hours +" "+((hours==1)?"hour":"hours")+"</div>";}
out += '<div class="mins">'+mins +" "+((mins==1)?"min":"mins")+"</div>";
out += '<div class="secs">'+secs +" "+((secs==1)?"sec":"secs")+"</div>";

Is there any way to change the design for the wordings with different styles? Let say, "days","hours" is red in color, and the digits are green in color?

Well, it wasn't really made to support it, but in the wording for each you could plug in HTML. It should work as long as the wording does not contain a " quote symbol. eg use:
<span style='color:red'>mins</span>

You can center the countdown by changing the last line in the code to something like:

<div id="countbox1" style="text-align:center;"></div>

My language (Croatian) uses more than two names for things like "days." Here are the rules I have to use (hopefully someone in a similar situation might find them helpful):

LastDigitDays = days.toString().charAt(days.toString().length-1);
LastDigitHours = hours.toString().charAt(hours.toString().length-1);
LastDigitMins = mins.toString().charAt(mins.toString().length-1);

if(days!=0 && LastDigitDays=="1" && days!=11){out += days +" dan, ";}
else if(days!=0){out += days +" dana, ";}

if(hours==2 || hours==3 || hours==4){out += hours +" sata, ";}
else if(LastDigitHours=="1" && hours!=11){out += hours +" sat, ";}
else{out += hours +" sati, ";}

if(mins==12 || mins==13 || mins==14){out += mins +" minuta, ";}
else if(LastDigitMins=="2" || LastDigitMins=="3" || LastDigitMins=="4") {out += mins +" minute, ";}
else{out += mins +" minuta, ";}

Hi there, when the timer reaches its date would it be possible to change dateFuture to datePast to now count up?

Near the top directly under your dateFuture1 line, add these new lines:

day_of_month = 21;// what day of the calendary month to countdown to

dateNow = new Date();
dateFuture1.setDate(day_of_month);
dateFuture1.setFullYear(dateNow.getFullYear());

if(dateNow.getDate()>day_of_month){//if it's past that day of the month, set currentc month+1
dateFuture1.setMonth(dateNow.getMonth()+1);
}
else{//month is current month
dateFuture1.setMonth(dateNow.getMonth());
}
Where day_of_month is set to the calendar day of the month you want to count down to. That should automatically reset the countdown each month when you pass that day.

Near the top directly under your dateFuture1 line, add these new lines:

day_of_week = 0;//0=sunday, 6=saturday

dateNow = new Date();
if(dateNow.getDay()>day_of_week)day_of_week+=7;
dateFuture1.setDate(dateNow.getDate()+(day_of_week-dateNow.getDay()));//sets day of month
dateFuture1.setFullYear(dateNow.getFullYear());//Sets year (four digits)
dateFuture1.setMonth(dateNow.getMonth());//sets month (from 0-11)
Where day_of_week is the day of the week you want to count down to (0=Sunday, 3=Wednesday, 6=Saturday). That should automatically reset the countdown each week. If it is the day the countdown expires AFTER the countdown hour has past, it will show "Now!" until it rolls over to the next day where it will restart.

Near the top directly under your dateFuture1 line, add these new lines:

dateNow = new Date();
dateFuture1.setDate(dateNow.getDate()+1);//sets day of month
dateFuture1.setFullYear(dateNow.getFullYear());//Sets year (four digits)
dateFuture1.setMonth(dateNow.getMonth());//sets month (from 0-11)

That will automatically set the countdown day to "tomorrow" at whatever time you originally specified.

Change your dateFuture1 line to:
dateFuture1 = (new Date()).getTime()+(40*60*1000);//40 mins * 60 secs * 1000ms from nowand change:
amount = ddate.getTime() - dateNow.getTime();to
amount = ddate - dateNow.getTime();
Where your (40*60*1000) is your own math for how long in milliseconds after the page has loaded until the timer expires. In this case (40*60*1000) = 2400000 milliseconds = 40 minutes after page load.

I want to say thanks first of all, this is an excellent tutorial!

I'm looking to set Next Day Delivery countdown on pages, but need it to autoset to 14:00 every day (the cut-off time for NDD ordering), and say "NEXT DAY DELIVERY UNAVAILABLE" from 14:00 on Fri until 00:01 Monday. I have no idea how to do this although I have tried.

First of all, this is awesome and thank you for creating this, it's a useful piece of code. I'm wondering, how would you go about changing the color of the text when the countdown hit 5 mins?

Below:
amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs

Add this if() so it looks like:

amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs

if(amount<=300) document.getElementById(iid).style.color="#ff0000";

Where (amount<=300) is the condition using the number of seconds and #ff0000 is the color.

Is there anyway to make this timer show only business days left (count on M-F) minus holidays? I was looking to have two timers on my site. One that shows total days remaining and a second showing "business days".

The amount of M-F days between two dates could be done, but skipping holidays would be very difficult. Javascript doesn't store any holiday info and making a manual list account for things like Thanksgiving and "Federal holidays that are always on a Monday" would quickly get messy.