Java Reference
In-Depth Information
Save the code as ch5 _ example6.html . When you load the page in your browser, you should see a
correctly formatted sentence telling you the current date.
The first thing you do in the code is declare an array and populate it with the months of a year. Why
do this? Well, there is no method of the Date object that'll give you the month by name instead of as
a number. However, this poses no problem; you just declare an array of months and use the month
number as the array index to select the correct month name:
var months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
Next you create a new Date object, and by not initializing it with your own value, you allow it to
initialize itself to the current date and time:
var dateNow = new Date();
Following this you set the yearNow variable to the current year, as returned by the getFullYear()
method:
var yearNow = dateNow.getFullYear();
You then populate your monthNow variable with the value contained in the array element with an index
of the number returned by getMonth() . Remember that getMonth() returns the month as an integer
value, starting with 0 for January—this is a bonus because arrays also start at 0 , so no adjustment is
needed to find the correct array element:
var monthNow = months[dateNow.getMonth()];
Finally, you put the current day of the month into the variable dayNow :
var dayNow = dateNow.getDate();
Next you use a switch statement, which you learned about in Chapter 3. This is a useful technique for
adding the correct suffix to the date that you already have. After all, your application will look more
professional if you can say "it is the 1st day" , rather than "it is the 1 day" . This is a little
tricky, however, because the suffix you want to add depends on the number that precedes it. So, for the
first, twenty‐first, and thirty‐first days of the month, you have this:
switch (dayNow) {
case 1:
case 21:
case 31:
daySuffix = "st";
break;
For the second and twenty‐second days, you have this:
case 2:
case 22:
daySuffix = "nd";
break;
Search WWH ::




Custom Search