The Date object provides a sophisticated set of methods for manipulating dates and times. Working with some of the more advanced methods that Date provides can be a bit confusing, unless you understand the relationship between Greenwich Mean Time (GMT), Coordinated Universal Time (UTC), and local time zones. Fortunately, for the vast majority of applications, you can assume that GMT is the same as UTC and that your computer’s clock is faithfully ticking away GMT and is aware of your particular time zone.
There are several facts to be aware of when working with JavaScript date values:
JavaScript stores dates internally as the number of milliseconds since the “epoch,” January 1st, 1970 (GMT). This is an artifact of the way UNIX systems store their time and can cause problems if you wish to work with dates prior to the epoch in older browsers.
When reading the current date and time, your script is at the mercy of the client machine’s clock. If the client’s date or time is incorrect, your script will reflect this fact.
Days of the week and months of the year are enumerated beginning with zero. So day 0 is Sunday, day 6 is Saturday, month 0 is January, and month 11 is December. Days of the month, however, are numbered beginning with one.
The syntax of the Date() constructor is significantly more powerful than other constructors we have seen. The constructor takes optional arguments permitting the creation of Date objects representing points in the past or future. Table 7-1 describes constructor arguments and their results.
Argument |
Description |
Example |
---|---|---|
None |
Creates object with the current date and time. |
var rightNow = new Date(); |
"month dd, yyyy hh:mm:ss" |
Creates object with the date represented by the specified month, day (dd ), |
var birthDay = new Date("March 24, 1970"); |
Milliseconds |
Creates object with date represented as the integer number of milliseconds after the epoch. |
var someDate = new Date(795600003020); |
yyyy, mm, dd |
Creates object with the date specified by the integer values year (yyyy), |
var birthDay = new Date(1970, 2, 24); |
yyyy, mm, dd, hh, mm, ss |
Creates object with the date specified by the integer values for the year, month, day, hours, minutes, and seconds. |
var birthDay = new Date(1970, 2, 24, 15, 0, 0); |
yyyy, mm, dd, hh, mm, ss, ms |
Creates object with the date specified by the integer values for the year, month, day, hours, seconds, and milliseconds. |
var birthDay = new Date(1970, 2, 24, 15, 0, 250); |
Table 7-1 warrants some commentary. The string version of the constructor argument can be any date string that can be parsed by the Date.parse() method. In the syntax of the last two formats, the arguments beyond the year, month, and day are optional. If they are omitted, they are set to zero. The final syntax that includes milliseconds is available only in JavaScript 1.3+.
Note |
Because of the ambiguity that arises from representing the year with two digits, you should always use four digits when specifying the year. This can be done using the getFullYear() method discussed later in this section. |
It is important to note that Date objects you create are static. They do not contain a ticking clock. If you need to use a timer of some sort, the setInterval() and setTimeout() methods of the Window object are much more appropriate. These other methods are discussed both in Appendix B and in later application-oriented chapters.
Date objects are created to be picked apart and manipulated and to assist in formatting dates according to your specific application. You can even calculate the difference between two dates directly:
var firstDate = new Date(1995, 0, 6);var secondDate = new Date(1999, 11, 2);var difference = secondDate - firstDate;alert(difference);
The result indicates the approximate number of milliseconds elapsed between January 6, 1995, and December 2, 1999:
Converting this last example to a more usable value isn’t difficult and is discussed next.
To hide the fact that Date objects store values as millisecond offsets from the epoch, dates are manipulated through the methods they provide. That is, Date values are set and retrieved by invoking a method rather than setting or reading a property directly. These methods handle the conversion of millisecond offsets to human-friendly formats and back again for you automatically. The following example illustrates a few of the common Date methods:
var myDate = new Date();var year = myDate.getYear();year = year + 1;myDate.setYear(year);
alert(myDate);
This example gets the current date and adds one year to it. The result is shown here:
JavaScript provides a comprehensive set of get and set methods to read and write each field of a date, including getDate(), setDate(), getMonth(), setMonth(), getHours(), setHours(), getMinutes(), setMinutes(), getTime(), setTime, and so on. In addition, UTC versions of all these methods are also included: getUTCMonth(), getUTCHours(), setUTCMonth(), setUTCHours(), and so forth. One set of methods requires a special comment: getDay() and setDay(). These are used to manipulate the day of the week that is stored as an integer from 0 (Sunday) to 6 (Saturday). An example that illustrates many of the common Date methods in practice is shown here (the results are shown in Figure 7-1):
var today = new Date(); document.write("The current date : "+today+"<<br />>"); document.write("Date.getDate() : "+today.getDate()+"<<br />>"); document.write("Date.getDay() : "+today.getDay()+"<<br />>"); document.write("Date.getFullYear() : "+today.getFullYear()+"<<br />>"); document.write("Date.getHours() : "+today.getHours()+"<<br />>"); document.write("Date.getMilliseconds() : "+today.getMilliseconds()+"<<br />>"); document.write("Date.getMinutes() : "+today.getMinutes()+"<<br />>"); document.write("Date.getMonth() : "+today.getMonth()+"<<br />>"); document.write("Date.getSeconds() : "+today.getSeconds()+"<<br />>"); document.write("Date.getTime() : "+today.getTime()+"<<br />>"); document.write("Date.getTimezoneOffset() : "+today.getTimezoneOffset()+"<<br />>"); document.write("Date.getYear() : "+today.getYear()+"<<br />>");
A complete list of methods supported by Date objects is given in Appendix B.
There are a variety of ways to convert Date objects to strings. If you need to create a date string of a custom format, the best way to do so is to read the individual components from the object and piece the string together manually. If you want to create a string in a standard format, Date provides three methods to do so. These methods are toString(), toUTCString(), and toGMTString(), and their use is illustrated in the next example. Note that toUTCString() and toGMTString() format the string according to Internet (GMT) standards, whereas toString() creates the string according to “local” time. The result is shown in Figure 7-2.
var appointment = new Date("February 24, 1996 7:45"); document.write("toString():", appointment.toString()); document.write("<<br />>"); document.write("toUTCString():", appointment.toUTCString()); document.write("<<br />>"); document.write("toGMTString():", appointment.toGMTString());
Because you can pass the Date() constructor a string, it seems reasonable to assume that JavaScript provides a mechanism to convert strings into Date objects. It does so through the class method Date.parse(), which returns an integer indicating the number of milliseconds between the epoch and its argument. Notice that this method is a property of the Date constructor, not of individual Date instances.
The parse() method is very flexible with regard to the dates it can convert to milliseconds (the complete details of the method are found in Appendix B). The string passed as its argument can, naturally, be a valid string of the form indicated in Table 7-1. Also recognized are standard time zones, time zone offsets from GMT and UTC, and the month/day/year triples formatted with - or / separators, as well as month and day abbreviations like “Dec” and “Tues.” For example,
// Set value = December 14, 1982 var myDay = "12/14/82"; // convert it to milliseconds var converted = Date.parse(myDay); // create a new Date object var myDate = new Date(converted); // output the date alert(myDate);
creates myDate with the correct value shown here:
If you are not sure whether the particular string you wish to convert will be recognized by Date.parse(), you need to check the value it returns. If it cannot convert the given string to a date, the method returns NaN. For example, the invocation in this example,
var myDay = "Friday, 2002"; var invalid = Date.parse(myDay);
results in NaN because myDay does not contain enough information to resolve the date.
The nuances of the Date object should not be underestimated. Recall that ECMA-262 is the standard governing core JavaScript language features. While most aspects of browser implementations adhere to the specification rigorously, deviation in Date object behavior is commonplace. For example, Date support in very old browsers, particularly Netscape 2, is atrocious. There are so many bugs that the programmer is advised to avoid all but the simplest date operations on this platform. Netscape 3 is better, but still has problems handling time zones correctly. At the very least, caution should be exercised when manipulating dates in these two versions of Netscape. Internet Explorer 3 does not allow dates prior to the epoch. However, Netscape 4+ and Internet Explorer 4+ can handle dates hundreds and thousands of years before or after the epoch, which should be enough to handle most tasks. Of course, using extreme dates such as prior to 1 A.D. or far in the future should be done with caution. Appendix B contains full details on the various Date methods and implementation issues.