Java Reference
In-Depth Information
}
if (nowSecond < 10)
{
nowSecond = “0” + nowSecond;
}
These lines are there just for formatting reasons. If the time is nine minutes past 10, then you expect to see
something like 10:09. You don't expect 10:9, which is what you would get if you used the getMinutes()
method without adding the extra zero. The same goes for seconds. If you're just using the data in cal-
culations, you don't need to worry about formatting issues — you do here because you're inserting the
time the code executed into the web page.
Next, in a series of if statements, you decide (based on the time of day) which greeting to create for
displaying to the user.
if (nowHour < 12)
{
greeting = “Good Morning”;
}
else if (nowHour < 17)
{
greeting = “Good Afternoon”;
}
else
{
greeting = “Good Evening”;
}
Finally, you write out the greeting and the current time to the page.
document.write(“<h4>” + greeting + “ and welcome to my website</h4>”);
document.write(“According to your clock the time is “);
document.write(nowHour + “:” + nowMinute + “:” + nowSecond);
In Chapter 10 you'll see how you can write a continuously updating time to the web page, making it
look like a clock.
Setting Time Values
When you want to set the time in your Date objects, you have a series of methods similar to those used
for getting the time:
setHours()
setMinutes()
setSeconds()
setMilliseconds()
These work much like the methods you use to set the date, in that if you set any of the time parameters
to an illegal value, JavaScript assumes you mean the next or previous time boundary. If it's 9:57 and you
set minutes to 64 , the time will be set to 10:04 — that is, 64 minutes from 9:00.
Search WWH ::




Custom Search