Its a Date

Filed: Thu, Dec 14 2006 under Programming|| Tags: date countdown timer timers javascript

Javascript's date object is one of the most robust time/date libraries in any language, but even battle-hardened code warriors may only tap the surface of the object's capabilities. To that end, grab a snorkel and prepare to get your hands wet as we dive below the surface and find out exactly what makes a javascript Date tick by making a simple countdown timer.

Every single date in Javascript is an expression of how many milliseconds have passed since January 1, 1970. Presently, this value is: . Dates prior to January 1, 1970 are negative numbers with -1000 being a 11:59:59pm December 31, 1969, whereas +1000 is 12:00:01am January 1, 1970.

Given this one number alone Javascript can figure out the day of the week, the month of the year, and pretty much anything else you ever wanted to know about the date and time this integer represents.

Using an integer to represent a specific date/time is referred to as a Julian date (Wikipedia), or Julian Day Number. There are several different Julian Date systems and most all of them use different starting dates for their integers. Cobol and ANSI for instance use January 1, 1601, NASA uses May 24, 1968, and Javascript uses January 1, 1970.

Since a javascript date is actually an integer it makes it rather simple to do things like countdown timers. Lets say we want to do a countdown timer to count down to the new year.

   var Today   = new Date();
   var NewYear = new Date('January 1, '+(Today.getFullYear+1));
   var Countdown = NewYear.getTime()-Today.getTime();

This creates two new date objects. Today has an integer value of while NewYear has an integer value of . To get the difference between the two dates we just subtract Today from NewYear to get .

represents the number of milliseconds between the two dates. This means simply dividing this number by 1,000 will yield the number of seconds between the two dates. Dividing that by 60 will yield the number of minutes. Dividing that by 60 will yield the number of hours, and dividing that by 24 will yield the number of days.

   var scratch=Math.floor(Countdown/1000);     // Discard milliseconds
   var seconds=scratch % 60;                   // Get modulus 60 for seconds
   scratch = Math.floor((scratch-seconds)/60); // Discard seconds.
   var minutes=scratch % 60;                   // Get modulus 60 for minutes
   scratch = Math.floor((scratch-minutes)/60); // Discard minutes.
   var hours=scratch%24;                       // Get modulus 24 for hours
   scratch = Math.floor((scratch-hours)/24);   // Discard Hours
   var days=scratch;                           // Only days remain.

This gives us...


Now that we know how to get the differences between two dates, it's easy enough to make a countdown timer. Don't get too cocky though! A little later on you'll see how to make our countdown timer do a surprising little trick. What countdown timer? Why, this one...

// The span or div where we put the countdown timer.
// This is global so we don't have to look it up every single tick.   
var countdownspan = document.getElementById('countdown');     

function doCountdown( targetDate, autoCount ) {         // Countdown timer.

   // targetDate is a string representing the destination date.
   // if autoCount is true the timer will automatically update every second.
   // if autoCount is false the function will display the remaining time
   // once and then terminate.

   function padZero(val) {
      // This sub-function accepts a number (val) and if less than 10
      // will return '0'+val so 5 becomes 05, 9 becomes 09, etc.
   
      if (val < 10) {                                   // Is val less than 10?
         return '0'+val;                                // Yes, insert a zero
      } else {                                          // val is not less than 10
         return val;                                    // so just return the number
      }                                                 // without doing anything 
   }                                                    

   var Today = new Date();                              // Get current time/date
   var NewYear = new Date(targetDate);                  // Get target time/date
   var Countdown = NewYear.getTime()-Today.getTime();   // Calculate Difference

   if (Countdown >= 0) {
      // We still have some time left before we reach the target date
      
      var scratch=Math.floor(Countdown/1000);           // Discard miliseconds
      var seconds=scratch % 60;                         // Get modulus 60 for seconds
      scratch = Math.floor((scratch-seconds)/60);       // Discard seconds.
      var minutes=scratch % 60;                         // Get modulus 60 for minutes
      scratch = Math.floor((scratch-minutes)/60);       // Discard minutes.
      var hours=scratch%24;                             // Get modulus 24 for hours
      scratch = Math.floor((scratch-hours)/24);         // Discard Hours
      var days=scratch;                                 // Only days remain.

      // Put the result into the div/span
      countdownspan.innerHTML = days+' days, ' + hours+':'+padZero(minutes)+':'+padZero(seconds);
   } else {
      // Today's date is already past the target date.
      countdownspan.innerHTML = "You're too late!";
   }            

   if (autoCount) {
      // If true was passed for autoCount, call this function again in 1 second.
      setTimeout( "doCountdown('"+targetDate+"',true)", 1000);
   }            
}

To use this timer all you have to do is set up a span (or div) in your HTML with an ID of 'countdown'. Then call doCountdown('January 1, ', true); If you pass true, the countdown will update every second, if you pass false it will show the difference between now and your target date only once.

Now it's IMPORTANT to remember that you need your getElementById('countdown') calculated AFTER your countdown span/div is declared in the html. You can do this with an onLoad call in your BODY tag, or just have another script block lower down in your HTML. So if you copied and pasted the function and it's not doing what you want or you're getting errors make sure that your span/div declaration is above the javascript that does the getElementById('countdown') lookup.

With your function all set up you should now have a nice countdown timer like this -- -- counting down on your page somewhere.

Now the trick I promised you earlier. One of the most fundamental mistakes people make when working with javascript dates on the web is they forget that the visitor to the site has a fairly good chance of not being in the same timezone as the web server which might not even be in the same timezone as you!

Since we haven't used any timezones at all in this tutorial, javascript is going to always use the visitor's timezone. But lets say your countdown is counting down to a shuttle liftoff, or the new year's eve ball dropping in New York City, or the official Greenwich Mean Time new year. Fear not, Javascript's date parser is very adept at letting you specify a very specific time. In this case all you have to do is specify the timezone of your target date. Here are a few examples....

       doCountdown( 'January 1,  EST', true); -- Destination is Eastern Standard Time
       doCountdown( 'January 1,  GMT', true); -- Destination is Greenwich Mean Time

And with that, this article has officially run out of time. 0 days, 0:00:00