↑
Main Page
ECMA-262
This line creates a new
Date
object with the current date and time. You can also set the date and time
value when creating a new
Date
object in one of two ways. The first is to just specify the number of
milliseconds since 12 AM on January 1, 1970:
var d = new Date(0);
Two class methods (which would be static methods in Java) called
parse()
and
UTC()
can also be used
in conjunction with this method of creating
Date
objects. The
parse()
method accepts a string as an
argument and tries to convert that string into a date value (meaning the millisecond representation).
ECMA-262 doesn’t define the date formats that the
parse()
method accepts, so this is purely imple-
mentation-specific and often locale-specific. For instance, in the United States, most implementations
support the following date formats:
?
mm/dd/yyyy (such as 6/13/2004)
?
mmmm dd, yyyy (such as January 12, 2004)
For instance, if you wanted to create a
Date
object for May 25, 2004, you could use the
parse()
method
to get the millisecond representation and then pass that value into the
Date
constructor:
var d = new Date(Date.parse(“May 25, 2004”));
If the string passed in to
parse()
can’t be turned into a date, the function returns
NaN
.
The
UTC()
method also returns the millisecond representation of a date, but with different arguments:
year, month, day of the month, hours, minutes, seconds, and milliseconds. When using this method,
you must always specify the year and month, but the other information is optional. Be very careful
when setting the month because the values go from 0 to 11, where 0 is equal to January and 11 is equal
to December, so to set a date equal to February 5, 2004, you do this:
var d = new Date(Date.UTC(2003, 1, 5));
Here, the
1
represents February, the second month. This is obviously a very important difference to keep
track of when accepting user input to create a date. The other information is as you would expect, with
the possible exception that the hours are given in military time (0 through 23) instead of AM/PM. So, to
set a date equal to February 5, 2004 at 1:05 PM, you use this code:
var d = new Date(Date.UTC(2003, 1, 5, 13, 5));
The second method of creating a date is to specify the same arguments that
UTC()
accepts directly:
var d = new Date(2003, 1, 5);
The arguments are specified in the same order, and they don’t all need to be present (except for the year
and month).
The
Date
class is one of the few that overrides
toString()
and
valueOf()
differently. The
valueOf()
method always return the millisecond representation of the date whereas the
toString()
method
returns a string in an implementation-specific, human-readable format. For this reason, it is impossible
to depend on the
toString()
method for any consistent behavior. As an example, in the United States,
78
Chapter 3
06_579088 ch03.qxd 3/28/05 11:36 AM Page 78
Free JavaScript Editor
Ajax Editor
©
→ R7