Create a script in HTML format that displays the current date and time and welcomes the user with “Good morning!”, “Good afternoon!”, or “Good evening!”, depending on the time of day.
1. Type the <!DOCTYPE> declaration, <html> element, header information, and the <body> element. Use the strict DTD and “Welcome” as the content of the <title> element.
2. Add the following text and elements to the document body:
<h1>Welcome to my Web Page</h1>
3. Add the following script section to the end of the document body:
<script type=”text/javascript”>
/* <![CDATA[ */
/* ]]> */
</script>
4. Add the following variable declarations to the script section. The first variable
instantiates a Date object. The second and third variables will be assigned text strings
containing a greeting and the current time. The fourth and fifth variables are assigned
the minute and hour values from the Date object.
var dateObject = new Date();
var greeting = “”;
var curTime = “”;
var minuteValue = dateObject.getMinutes();
var hourValue = dateObject.getHours();
5. Add the following code to the end of the script section. The first if statementevaluates the minuteValue variable and adds a 0 to the beginning of the value if it is less than 10. This forces the minutes to always display as two decimals. The if…else structure evaluates the hourValue variable and builds the strings that are assigned to the greeting and curTime variables.
if (minuteValue < 10)
minuteValue = “0” + minuteValue;
if (hourValue < 12) {
greeting = “<p>Good morning! ”
curTime = hourValue + “:” + minuteValue + ” AM”;
}
else if (hourValue == 12) {
greeting = “<p>Good afternoon! “;
curTime = hourValue + “:” + minuteValue + ” PM”;
}
else if (hourValue < 17) {
greeting = “<p>Good afternoon!”
curTime = (hourValue-12) + “:” + minuteValue + ” PM”
}
else {
greeting = “<p>Good evening! ”
curTime = (hourValue-12) + “:” + minuteValue + ” PM”
}
6. Add the following arrays to the end of the script section. These arrays contain the full text for days and months.
var dayArray = new Array(“Sunday”, “Monday”, “Tuesday”,
“Wednesday”, “Thursday”, “Friday”, “Saturday”);
var monthArray = new Array(“January”, “February”, “March”,
“April”, “May”, “June”, “July”, “August”, “September”, “October”,
“November”, “December”);
7. Type the following statements at the end of the script section to retrieve the current day and month values from the dateObject variable:
var day = dateObject.getDay();
var month = dateObject.getMonth();
8. Finally, add the following statement to the end of the script section to display the
current date and time and a welcome message:
document.write(“<p>”+ greeting + “It is ” + curTime
+ ” on ” + dayArray[day] + “, ” + monthArray[month]
+ ” ” + dateObject.getDate() + “, ” + dateObject.
getFullYear() + “.</p>”);
9. Save the file as WelcomeDateTime.html
** The document when opened in your Web browser should show the appropriate welcome message along with the time and date.**
