g
Printer Friendly Version

editor  
BellaOnline's JavaScript / Java Editor
 

A Simple JavaScript Countdown

Blogger Widget BoxI wanted a simple JavaScript countdown timer that I could put in a Blogger widget box, or use in context in a web page. Initially, I assumed that I could easily find exactly what I was looking for with a quick web search. However, all of the counters I found were much more complicated than what I was looking for. I didn't want to count down to the last second, I just cared about days. So, I decided to write my own.

The following code is configured to count days until (or from) August 8th, 2008. Because 8 is an auspicious number in Chinese culture, this day was chosen for the opening ceremonies of the 2008 Summer Olympics in Beijing.

<script type="text/javascript">
var millisecs_per_day=86400000
// set countdown time in milliseconds
// put desired day as arguments to Date.UTC
// in the order:
// year, month (remember January is 0), day of month, offset from GMT
// NOTE: we are using the offset because that represents midnight
//     (beginning of the day) in a specific timezone
var countdown_time=Date.UTC(2008,7,8,-8);
// get the current time and convert to milliseconds
var now=new Date();
var now_millisecs=now.valueOf();

var day_cnt= Math.ceil(( countdown_time - now_millisecs)/86400000 )

// display the number of days left (or since)
if ( day_cnt > 1 )
{
     // multiple days to go
     document.write( day_cnt + " days to go")
}
else if ( day_cnt == 1 )
{
     // one day to go
     document.write( day_cnt + " day to go")
}
else if ( day_cnt == 0 )
{
     // it's today
     document.write( "today")
}
else if ( day_cnt == -1 )
{
     // one day ago
     document.write( day_cnt + " day ago")
}
else
{
     // multiple days ago
     document.write( day_cnt + " days ago")
}
</script>


You can download this code or see it in action here. To use this code in your own projects, copy and paste it into your web page (or a Blogger HTML/JavaScript widget box, as shown in the picture above.) Change the date according to the instructions in the comments – if this is confusing, you may find my article on Introduction to UTC Dates helpful.

This site needs an editor - click to learn more!

JavaScript / Java Site @ BellaOnline
View This Article in Regular Layout

Content copyright © 2013 by Julie L Baumler. All rights reserved.
This content was written by Julie L Baumler. If you wish to use this content in any manner, you need written permission. Contact Editor Wanted for details.



| About BellaOnline | Privacy Policy | Advertising | Become an Editor |
Website copyright © 2023 Minerva WebWorks LLC. All rights reserved.


BellaOnline Editor