start page | rating of books | rating of authors | reviews | copyrights

JavaScript: The Definitive Guide

Previous Chapter 21
JavaScript Reference
Next
 

Date Object

Name

Date Object---manipulate dates and times

Availability

Navigator 2.0, Internet Explorer 3.0

Constructor

To create a Date object, use one of the following five syntaxes:

new Date();
new Date(milliseconds)
new Date(datestring);
new Date(year, month, day);
new Date(year, month, day, hours, minutes, seconds)

With no arguments, the Date() constructor creates a Date object set to the current date and time. Otherwise, the arguments to Date() specify the date, and, optionally, the time for the new object. Note that in the third through fifth syntaxes above, the specified times are interpreted as local times, not Greenwich Mean Time (GMT) times.

Date() can also be used as a function instead of a constructor. When invoked without the new operator, and without any arguments, Date() does not create a Date object but instead returns a string that represents the current date and time for the local time zone. Calling Date() without the new operator is equivalent to using it with the new operator to create a Date object and then using the toString() method of that object to convert the date to a string.

When used as a constructor, the arguments to Date(), are the following:

Arguments

milliseconds

The number of milliseconds between the desired date and midnight GMT on January 1st, 1970. For example passing the argument 5000 would create a date that represents five seconds past midnight on 1/1/70.

datestring

A single argument that specifies the date and, optionally, the time as a String. The string should have the format month day, year hours:minutes:seconds where month is the English name of the month, and hours are specified in 24-hour format. For example:

new Date("December 31, 1999 23:59:59");

The seconds field or the entire time specification may be omitted from this format.

year

The year, in four-digit format. For example, specify 2001 for the year 2001. For years within the 20th century, you can also subtract 1900 and specify the date in two-digit format. For example, you could specify 97 for the year 1997.

month

The month, specified as an integer from 0 (January) to 11 (December)

day

The day of the month, specified as an integer from 1 to 31. Note that this argument uses 1 as its lowest value, while other arguments use 0 as their lowest value.

hours

The hour, specified as an integer from 0 (midnight) to 23 (11 p.m.).

minutes

The minutes in the hour, specified as an integer from 0 to 59.

seconds

The seconds in the minute, specified as an integer from 0 to 59.

Returns

The newly created Date object.

Methods

Once a Date object is created by using Date() as a constructor in any of the forms shown above, any of the following methods can be used to operate on the Date object. Note that unlike most JavaScript objects, the Date object has no properties that can be read and written directly; instead, all access to date and time fields is done through these methods.

getDate()

Return the day of the month of a Date object.

getDay()

Return the day of the week of a Date object.

getHours()

Return the hours field of a Date object.

getMinutes()

Return the minutes field of a Date object.

getMonth()

Return the month field of a Date object.

getSeconds()

Return the seconds field of a Date object.

getTime()

Return the internal, millisecond representation of a Date object.

getTimezoneOffset()

Return the time zone difference, in minutes, between this date and GMT.

getYear()

Return the year field of a Date object.

parse()

Parse a string representation of a date, and return it in millisecond format.

setDate()

Set the day of the month field of a Date object.

setHours()

Set the hour field of a Date object.

setMinutes()

Set the minutes field of a Date object.

setMonth()

Set the month field of a Date object.

setSeconds()

Set the seconds field of a Date object.

setTime()

Set the fields of a Date object using the millisecond format.

setYear()

Set the year field of a Date object.

toGMTString()

Convert a Date to a string, using the GMT time zone.

toLocaleString()

Convert a Date to a string, using the local time zone.

UTC()

Convert a numeric date and time specification to millisecond format.

Description

The Date object is a datatype built into the JavaScript language. Unlike most other JavaScript object types, the Date object does not represent any HTML construct in the current document. Instead, it is an independent object that can be created and manipulated freely by JavaScript code. Date objects are created with the new Date() syntax shown in the Constructor section above.

Note that when the Date() constructor is used without the new operator, and is called with no arguments, it does not create a Date object but instead simply returns a string containing the current date and time in the local time zone. Calling Date() in this way is equivalent to creating a Date object to represent the current date and time and then calling the toString() method of that object:

(new Date()).toString()

Once a Date object is created, there are a number of methods that allow you to operate on it. Most of the methods simply allow you to get and set the year, month, day, hour, minute, and second fields of the object. The toGMTString() and toLocaleString() methods convert dates to human-readable strings. getTime() and setTime() convert to and from the internal representation of the Date object--the number of milliseconds since midnight (GMT) on January 1st, 1970. In this standard "millisecond format", a date and time are represented by a single integer, which makes date arithmetic particularly easy.

Most of the Date object methods are invoked through an instance of the Date object. For example:

d = new Date();  // get today's date and time
system.write('Today is: " + d.toLocaleString());  // and print it out

There are two functions, however, that have Date in their name, but are not methods, and do not operate on a Date object. These functions, Date.parse() and Date.UTC(), are useful for converting dates to millisecond format. Note though that they do not use the Date object, and are therefore not invoked through a Date object.

Usage

Because JavaScript code may be run on machines all over the world, you need to pay attention to time zone differences. The syntax for creating Date objects shown above assumes that date and time values are specified in local time. While this is appropriate in some cases, there are many cases when it is not. When your code must work the same independently of the time zone in which it is run, you should specify all your hardcoded dates in the GMT (or UTC) time zone. You can then use the Date.UTC() method to convert these date specifications to a time zone-independent number of milliseconds. You can then use this number of milliseconds directly, or can use it to create a Date object.

Bugs

In Navigator 2.0, the Date object has quite a few bugs and is almost unusable. On Macintosh platforms, the time returned is off by an hour. There appears to be something wrong with the Navigator implementation of Date.toGMTString. On all platforms, time zones are not handled well, and prior to version 2.0.2, there are difficulties handling daylight savings time. A side effect of this is that Navigator 2.0 and 2.0.1 cannot correctly determine whether a document on a server is newer than the cached version and so the Reload button does not always work correctly.

You can usually use the Date object to print out the current date, and you can use it to compute the interval (in milliseconds) between two dates or times in the same time zone, but you should probably not attempt more sophisticated uses of it than that.

Example

The most common use of the Date object (and probably the only particularly interesting use) is to subtract the millisecond representations of the current time from some other time to determine the difference between the two times. The following example shows two such uses:

<SCRIPT language="JavaScript">
today = new Date(); make a note of today's date
christmas = new Date(); get a date with the current year
christmas.setMonth(11); set the month to December...
christmas.setDate(25);  ...and the day to the 25th
// If Christmas hasn't already passed, compute the number of
// milliseconds between now and Christmas, then convert this
// to a number of days and print a message.
if (today.getTime() < christmas.getTime()) { 
    difference = christmas.getTime() - today.getTime();
    difference = Math.floor(difference / (1000 * 60 * 60 * 24));
    document.write('Only ' + difference + ' days until Christmas!<P>');
}
</SCRIPT>
   ... rest of HTML document here ..
<SCRIPT language="JavaScript">
// Here we use Date objects for timing. We divide by 1000
// to convert milliseconds to seconds. We could divide
// further to convert to minutes, hours or days.
now = new Date();
document.write('<P>It took ' + 
    (now.getTime()-today.getTime())/1000 +
    'seconds to load this page.');
</SCRIPT>

See Also

"Date.parse()", "Date.UTC()"


Previous Home Next
confirm() Book Index Date.getDate()

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell