Java Reference
In-Depth Information
The first four statements of this function create four variables. The first,
lstCity
, contains a reference
to the
<select/>
element object. You create this variable for convenience purposes—namely for the
creation of the second variable:
selectedOption
:
var selectedOption = lstCity.options[lstCity.selectedIndex];
This
selectedOption
variable is retrieved by using the
lstCity
object's
options
property in
conjunction with its
selectedIndex
property, and now that you have the
selectedOption
, you can
easily get the information attached to the option:
var offset = selectedOption.value;
var selectedCity = selectedOption.text;
Next, you want to determine if the user checked the daylight savings check box:
var dstAdjust = 0;
if (myForm.chkDst.checked) {
dstAdjust = 60;
}
You initialize the
dstAdjust
variable with
0
. If the check box is checked, you modify
dstAdjust
to
contain the value of
60
. The value of
60
is for 60 minutes. As you have probably guessed, your time
conversion calculation will be with minute values.
In the final part of
updateTimeZone()
, you call the
updateTime()
function, passing the values
contained within the
selectedCity
,
offset
, and
dstAdjust
variables:
updateTime(selectedCity, offset, dstAdjust);
}
In the function
updateTime()
, you write the current local time and the equivalent time in the selected
city to the output elements.
You start at the top of the function by creating a new
Date
object, which is stored in the variable
now
. The
Date
object will be initialized to the current local time:
function updateOutput(selectedCity, offset, dstAdjust) {
var now = new Date();
Next, you output the local time to the
<span/>
element with an
id
of
spanLocalTime
:
document.getElementById("spanLocalTime").innerHTML = now.toLocaleString();
You use the
Date
object's
toLocaleString()
method to format the date and time in your region's
format.
You saw in Chapter 7 that if you set the value of a
Date
object's individual parts (such as hours,
minutes, and seconds) to a value beyond their normal range, JavaScript assumes you want to adjust the
date, hours, or minutes to take this into account. For example, if you set the hours to
36
, JavaScript