HTML and CSS Reference
In-Depth Information
Setting Date and Time Values
In addition to retrieving date and time values, you can also use the Date object method
to change these values. This is most often used in programs that involve setting the value
of a future date or time, such as an expiration date for an online membership or an
online calendar used for event scheduling. Figure 11-9 summarizes the methods sup-
ported by JavaScript for setting date and time values.
Figure 11-9
setting values within a date object
Method
Sets
dateObject .setSeconds( value )
the seconds value of dateObject to value
dateObject .setMinutes( value )
the minutes value of dateObject to value
dateObject .setHours( value )
the hours value of dateObject to value
dateObject .setDate( value )
the day of the month value of dateObject to value
dateObject .setMonth( value )
the month number of dateObject (0 = January,
1 = February, etc.) to value
dateObject .setFullYear( value )
the four-digit year value of dateObject to value
dateObject .setTime( value )
the time of dateObject in milliseconds since January 1,
1970 at 12:00 a.m. to value
For example, the following code shows how to use the setFullYear() method to change
the date stored in the thisDate variable from February 24, 2015 to February 24, 2016:
thisDate = new Date(“February 24, 2015”);
thisDate.setFullYear(2016);
In the same fashion, you'll create a function that uses the setFullYear() method in
the next session.
Creating a Date and Time Function
You'll use the methods associated with Date objects that you just learned to create func-
tions that extract the date and time values from specified dates, and then return those
values in formatted text strings. The first function you'll create is named showDate()
and has the following code:
JavaScript does not sup-
port daylight saving time
(also known as summer
time); instead, a com-
puter's operating system
makes adjustments for
daylight saving time when
needed.
function showDate(dateObj) {
thisDate = dateObj.getDate();
thisMonth = dateObj.getMonth()+1;
thisYear = dateObj.getFullYear();
return thisMonth + “/” + thisDate + “/” + thisYear;
}
The showDate() function has a single parameter named dateObj , which stores the Date
object to be evaluated. The function extracts the day of the month, the month number,
and the four-digit year value, and returns a text string combining all of the values in the
format
month / day / year
where month is the value of the thisMonth variable, day is the value of the thisDate vari-
able, and year is the value of the thisYear variable. You'll place the text generated by this
function into the dateNow field of the Web form on the clock Web page.
 
Search WWH ::




Custom Search