HTML and CSS Reference
In-Depth Information
To create the
today
variable:
◗
1.
Return to the
clock.htm
file in your text editor.
◗
2.
Insert the following lines at the beginning of the
NYClock()
function, as shown in
Figure 11-7:
// the today variable contains the current date and time
var today = new Date(“February 24, 2015 14:35:05”);
Figure 11-7
declaring the today variable
the today variable
stores a date object
◗
3.
Save your changes to the file.
Retrieving the Date, Month, and Year Values
A
Date
object stores a date and time as a numeric value that is equal to the number of
milliseconds between the specified date and time and January 1, 1970 at midnight. For
example, a
Date
object based on the date and time of February 24, 2015 at 2:35:05
p.m. has a hidden value equal to 1,424,810,105,000 milliseconds. Fortunately, you don't
have to work directly with this value! Instead, JavaScript provides methods you can use
to extract information from a
Date
object or to change a
Date
object's value.
To extract the day of the month from a given
Date
object, JavaScript provides the
getDate()
method
date
.getDate()
where
date
is a
Date
object or a variable that contains a
Date
object. For example, the
following code extracts the day value from the
thisDate
variable and stores the result in
the
thisDay
variable:
thisDate = new Date(“February 24, 2015 14:35:05”);
thisDay = thisDate.getDate();
After running these commands, the value of the
thisDay
variable is 24 because that is the
24
th
day of the month in the specified date.
In the same fashion, the
getMonth()
method extracts the month value with a value
of 0 representing January, 1 representing February, and so forth up to 11 represent-
ing December. Because the
getMonth()
method starts counting the months with 0 for
January, you may want to add 1 to the month number to translate the value to the com-
mon system of numbering months from 1 to 12. The following JavaScript code extracts
the current month number, increases it by 1, and stores it in the
thisMonth
variable:
thisDate = new Date(“February 24, 2015 14:35:05”);
thisMonth = thisDate.getMonth() + 1;
The resulting value for the
thisMonth
variable is 2, representing the second month of
the year.