Every year Christmas seems to come around more and more quickly - even before the Halloween pumpkins have been taken down everyone starts counting the number of days left until Christmas Day - whether it's children looking forward to Santa Claus coming, or their mother wondering if she's got enough time to buy their presents. Fortunately every web site designer can help with that process by adding a Javascript Christmas countdown to one of their web pages; and so the code for this Christmas countdown will need to:
- calculate the amount of time between the current time and Christmas day
- format the time and display it on the web page
- create a timer that will refresh the display
Working with Javascript Dates
The code for the Christmas countdown should (as always) be incorporated into a function:
The function uses two instances of the Javascript date object: one instance is used for the date of Christmas day; the other is used for the current date and time:
By default the date object is set to the current date and time, therefore the details for the Christmas date object needs to be modified with the correct details:
It's worth noting that the Javascript date object's month property starts with a value of 0 for January through to 11 for December.
Calculating the Time between Now and Christmas Day
The first step of the time calculation is to subtract the value of one date from the other; the result is actually in milliseconds (one thousandths of a second) and so the time difference in seconds can be found from:
From that the number of days can be calculated:
and then the number of hours:
the number of minutes:
and the number of seconds:
Displaying the Christmas Count Down
The result of the calculation now needs to be displayed - that's done by selecting an object (such as a div area) and then writing a formatted output to it:
Adding a Timer
Finally a timer can be added - this will recalculate the time difference and update the display once every second using the Javascript setTimeout function:
Now the count_down function just needs to be called:
The display will look something like:
Conclusion
The web page will, of course, need a div area for the output:
However, once that's done then the web page will happily count down until Christmas day; and the beauty of this code is that with just a minor change it will work for: New Year's Day; a birthday; a software launch date; or any other date that the web page user might find useful.
Further Reading
How to Create a Christmas Count Down in PHP