USE ARRAYS TO DISPLAY DATE INFORMATION
Using just the Date object alone, you can obtain accurate date
and time information for the user's computer. You can also combine this with
methods of the Date object to display individual pieces of the
date and time information. Although this does return accurate date
information, you may want to display the date a little more elegantly than is
possible with these methods alone.
The methods Date.getMonth() and Date.getDay()
return a number for the month and for the day of the week. You may want to
display the date as the name of the month, for example, rather than a number,
especially because the numbering for getMonth starts with 0 for
January. Similarly, you may want to display the day of the week as the name
of the day rather than a number.
You can create two simple arrays to hold the names of the months and days of the week, as follows:
var monthName = ["January","February","March","April","May", "June","July","August","September","October", "November","December"];
The array values are in quotations to indicate that they are string values.
var weekdayName = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
The next step is to associate the array values with the value from the
Date object. For the month names, use
Date.getMonth(), for example:
var tDate = new Date(); var tMonth = monthName[tDate.getMonth()];
The numeric value returned from Date.getMonth() is used to
specify the array index value for the name value in the
monthName array.
For the weekday name, use Date.getDay():
var tDay = weekdayName[tDate.getDay()];
To display the day of the week, month, day of the month, and year, you could use the following code in the head or the body section of your page:
<script type="text/javascript" language="JavaScript">
<!--
var tDate = new Date();
var monthName = ["January","February","March","April","May",
"June","July","August","September","October",
"November","December"];
var tMonth = monthName[tDate.getMonth()];
var weekdayName = ["Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday"];
var tDay = weekdayName[tDate.getDay()];
document.write("Welcome to my Web page." + "<br>");
document.write("Today's date is " + tDay + ", " + tMonth +
" " + tDate.getDate() + ", " + tDate.getFullYear() + ".");
// -->
</script>
