Time Shifts - Page 9
December 7, 2001
The Date object is not limited to the current time;
you can also create a Date object for a specific
date in the past or future. For example, to create a new
Date object for October 31, 2001, any of the
following is acceptable:
var then = new Date("October 31, 2001");
var then = new Date("October 31, 2001 00:00:00");
var then = new Date("Oct 31, 2001");
var then = new Date(2001, 9, 31);
Notice that you are passing a specific date to the new
Date object. In JavaScript terminology, the
information you pass to an object, whether it is a string of
characters, a number, or even another object, is called an
argument. When an object (or function) receives an
argument, the object uses the data to perform its job. In this
case, the Date object uses the argument to create a
Date object for the specified date.
This feature of the Date object is commonly used to
create countdowns to specific times or dates, such as
anniversaries, product launches, etc. So, if you need a script to
display the number of days between now and Halloween, create a
Date object for the current date, a
Date object for Halloween, and subtract to find the
difference. The script in Example 1-5 shows you how to do this.
Example 1-5: How long until Halloween?
<script language="JavaScript">
var now = new Date( );
var then = new Date("October 31, 2001");
var gap = then.getTime() - now.getTime( );
gap = Math.floor(gap / (1000 * 60 * 60 * 24));
document.write ("Only " + gap + " days \'til Halloween");
</script>
First, the script creates a new Date object named
now for the current date and another named
then for Halloween. The current date,
now.getTime( ), is then subtracted from Halloween's
date, then.getTime( ), and the resulting value (the
remaining time between the two dates) is stored in the variable
gap. So we have the difference in time between now
and Halloween in the variable gap, but there's a
problem: it's in milliseconds. We need to convert milliseconds to
days. We do this by dividing gap by the number of
milliseconds in a day (1000 milliseconds × 60 seconds
× 60 minutes × 24 hours):
gap / (1000 * 60 * 60 * 24)
The difference in time, which is now in days, is then rounded
down to the nearest full day with Math.floor( ).
Finally, the number of days is displayed on the page with
document.write( ).
Objects, Properties, And Methods - Page 8
Designing with JavaScript, 2nd Edition
|