Java Reference
In-Depth Information
document.write(“<h4>” + greeting + “ and welcome to my website</h4>”)
document.write(“According to your clock the time is “);
document.write(nowHour + “:” + nowMinute + “:” + nowSecond);
</script>
</body>
</html>
Save this page as ch5_examp7.htm . When you load it into a web browser, it writes a greeting based on
the time of day as well as the current time, as shown in Figure 5-6.
Figure 5-6
The fi rst two lines of code declare two variables — greeting and nowDate .
var greeting;
var nowDate = new Date();
The greeting variable will be used shortly to store the welcome message on the web site, whether this
is “Good Morning”, “Good Afternoon”, or “Good Evening”. The nowDate variable is initialized to a
new Date object. Note that the constructor for the Date object is empty, so JavaScript will store the cur-
rent date and time in it.
Next, you get the information on the current time from nowDate and store it in various variables. You
can see that getting time data is very similar to getting date data, just using different methods.
var nowHour = nowDate.getHours();
var nowMinute = nowDate.getMinutes();
var nowSecond = nowDate.getSeconds();
You may wonder why the following lines are included in the example:
if (nowMinute < 10)
{
nowMinute = “0” + nowMinute;
Search WWH ::




Custom Search