Java Reference
In-Depth Information
It's unlikely that you'll be using this way of defi ning a Date object very often, but this is how JavaScript
actually stores the dates. The other formats for giving a date are simply for convenience.
Next, you can pass a string representing a date, or a date and time. In the following example, you have
“31 January 2010”.
var theDate3 = new Date(“31 January 2010”);
However, you could have written 31 Jan 2010, Jan 31 2010, or any of a number of valid variations
you'd commonly expect when writing down a date normally — if in doubt, try it out. Note that Firefox
doesn't support the string “01-31-2010” as a valid date format.
If you are writing your web pages for an international audience outside the United States, you need to
be aware of the different ways of specifying dates. In the United Kingdom and many other places, the
standard is day, month, year, whereas in the United States the standard is month, day, year. This can
cause problems if you specify only numbers — JavaScript may think you're referring to a day when you
mean a month. The easiest way to avoid such headaches is to, where possible, always use the name of
the month. That way there can be no confusion.
In the fourth and fi nal way of defi ning a Date object, you initialize it by passing the following param-
eters separated by commas: year, month, day, hours, minutes, seconds, and milliseconds. For example:
var theDate4 = new Date(2010,0,31,15,35,20,20);
This date is actually 31 January 2010 at 15:35:20 and 20 milliseconds. You can specify just the date part if
you wish and ignore the time.
Something to be aware of is that in this instance January is month 0, not month 1, as you'd expect, and
December is month 11. It's very easy to make a mistake when specifying a month.
Getting Date Values
It's all very nice having stored a date, but how do you get the information out again? Well, you just use
the get methods. These are summarized in the following table.
Method
Returns
getDate()
The day of the month
getDay()
The day of the week as an integer, with Sunday as 0, Monday as 1, and so on
getMonth()
The month as an integer, with January as 0, February as 1, and so on
getFullYear()
The year as a four-digit number
toDateString()
Returns the full date based on the current time zone as a human-readable
string. For example, “Wed 31 Dec 2003”.
For example, if you want to get the month in ourDateObj, you can simply write the following:
theMonth = myDateObject.getMonth();
Search WWH ::




Custom Search