Calculating the difference between two dates
Lets begin this tutorial by getting to the heart of it:
For the scripts that follow, the above is our hero people, not some Hollywood actor. Date.getTime() is a prebuilt JS method that returns the time elapsed from January 1st, 1970 to the current Date instance, in milliseconds. Its superpower is not so much its long term memory, as impressive as that may be, but its knack for converting a date to a number (in milliseconds, but nevertheless). And we all know the easiest subjects to perform arithmetic on are numbers.
So here's the general premise for calculating the difference between two dates- convert both dates to a number using Date.getTime(), and subtract! To a few examples now.
Calculating days remaining until Christmas:
Notice how the year for "Christmas" is dynamically set to the current year (or nextyear if Christmas has already passed for this year), so the script is reusable now and in the future as well without having to modify it.
Calculating time expired since the Millennium (Jan 1st, 2000)
We all remember the Millennium and perhaps even the parties we attended. The following shows how many days has elapsed since then (count up):
Dynamically indicating what's new on your page:
Finally, how about displaying a "new" image alongside new content that will automatically disappear (the image, that is) after the specified future date has been reached? The logic is simple enough- if the current date is less than the specified future date, write out the "new" image:
Example: This is new content!