The Date object is a built-in JavaScript object that enables you to conveniently work with dates and times. You can create a Date object anytime you need to store a date, and use the Date object's methods to work with the date.
Note
JavaScript dates are stored as the number of milliseconds since midnight, January 1, 1970. This date is called theepoch. Dates before 1970 weren't allowed in early versions, but are now represented by negative numbers.
You can create a Date object using the new keyword. You can also optionally specify the date to store in the object when you create it. You can use any of the following formats:
birthday = new Date(); birthday = new Date("June 20, 2003 08:00:00"); birthday = new Date(6, 20, 2003); birthday = new Date(6, 20, 2003, 8, 0, 0);
You can choose any of these formats, depending on which values you wish to set. If you use no parameters, as in the first example, the current date is stored in the object. You can then set the values using the set methods, described in the next section.
A variety of set methods enable you to set components of a Date object to values:
As an example, the following statement sets the year of a Date object called holiday to 2003:
holiday.setFullYear(2003);
You can use the get methods to get values from a Date object. This is the only way to obtain these values, because they are not available as properties. Here are the available get methods for dates:
Note
Along with setFullYear and getFullYear, which require four-digit years, JavaScript includes setYear and getYear methods, which use two-digit year values. You should always use the four-digit version to avoid Year 2000 issues.
Finally, a few functions are available to help your Date objects work with local time values and time zones:
Along with these basic functions, JavaScript 1.2 and later include UTC versions of several of the functions described above. These are identical to the regular commands, but work with UTC instead of local time:
Two special methods of the Date object allow you to convert between date formats. Instead of using these methods with a Date object you created, you use them with the built-in object Date itself. These include the following: