Java Reference
In-Depth Information
</body>
</html>
Save the code as ch5_examp6.htm . If you load up the page, you should see a correctly formatted sen-
tence telling you what the current date is.
The fi rst 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 num-
ber as the array index to select the correct month name.
var months = new Array(“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 initial-
ize 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 fi nd the correct array element.
var monthNow = months[dateNow.getMonth()];
Finally, the current day of the month is put into variable dayNow.
var dayNow = dateNow.getDate();
Next you use a switch statement, which you learned about in the Chapter 3. This is a useful technique
for adding the correct suffi x 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 suffi x you want to add depends on the number that precedes it. So, for the fi rst,
twenty-fi rst, and thirty-fi rst 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