1. DATE AND TIME

All Web programming languages include some way to display the current date and time on an HTML page. The underlying code uses the computer's internal clock for this. If you're using a client-side language, such as JavaScript, the time displayed will be the time on the user's computer. If you're using a server-side language, such as ASP (Active Server Pages), the time displayed will be the time on the server.

You're not restricted to local time, however. You can calculate the time in any time zone on the globe, and you can also calculate time in UTC (Coordinate Universal Time). UTC is roughly the same as GMT (Greenwich Mean Time), or the time at the Greenwich meridian (longitude zero), five hours ahead of the U.S. Eastern Standard Time zone. UTC, however, is the time kept by time laboratories around the world, including the U.S. Naval Observatory, and is determined using highly precise atomic clocks.

2. TIME AND DATE IN JAVASCRIPT

JavaScript calculates dates as the number of milliseconds since the "epoch," which began on January 1, 1970. If you want to work with dates prior to this, it may cause problems in older browsers. You're not restricted to displaying dates in milliseconds, but when you ask JavaScript to calculate the difference between two dates, for example, it does this in milliseconds.

Date can include the month, the day of the month, the day of the week, and the year. The days of the month are numbered starting with 1. The days of the week are numbered starting with 0 -- day 0 is Sunday, day 1 is Monday, and so on.

3. THE JAVASCRIPT DATE OBJECT

JavaScript includes several built-in objects such as the Math object and the String object from previous lessons, and the Date object.

To create a new Date object:

var myDate = new Date();

The Date object can return date and time in many different forms, depending on the arguments (parameters) you provide. For example, if you display the variable myDate in an alert box:

var myDate = new Date();
alert (myDate);

The display varies depending on the browser. Figure 5.1 shows the alert box in Internet Explorer 6, and, as you can see, it includes day of the week, month, day of the month, hours, minutes, seconds, local time zone, and year.

Figure 5-1: Displaying the Date in Internet Explorer.
Figure 5-1: Displaying the Date in Internet Explorer.

Figure 5-2 shows the same code displayed in Netscape 7. It displays in this order: day of the week, month, day of the month, year, hours, minutes, seconds, and local time zone.

Figure 5-2: Displaying the Date in Netscape.
Figure 5-2: Displaying the Date in Netscape.

You can provide parameters so that the date displays with specific values:

  • yyyy,mm,dd: Displays date with these parameters for year, month, and day, the rest of the parameters are set to zero
// new Date (2003,9,12);
  • yyyy,mm,dd,hh,mm,ss: Adds specified hours, months, and seconds to the previous display
// new Date (2003,9,12,3,15,30);
  • milliseconds: Displays date based on number of milliseconds after the epoch
// new Date (7964000039);
This displays a date of Apr 2 21:13:20 1970

4. METHODS OF THE DATE OBJECT

The Date object includes many methods that allow you to both get (read) and set (write) each field of a date, and extract a specific field from the Date object. Important ones include:

Date.getDate()

// day of the month

Date.getMonth()

// month (numeric value, starting with 0 for January)

Date.getDay()

// day of the week (numeric value, starting with 0 for Sunday)

Date.getFullYear()

// four-digit year

Date.getHours()

// hours since midnight

Date.getMinutes()

// minutes

Date.getSeconds()

// seconds

Date.getMilliseconds()

// milliseconds

Date.getTime()

// number of milliseconds since the epoch

There are also methods to set all these, for example setDate(). The only exception is getDay() -- because day of the week is set by the other parameters of the date, there's no setDay() method.

5. USE DATE OBJECT METHODS

You can use these methods of the Date object to extract the date and time information you wish to display. Start by creating a new Date object and then use the Date object methods to pull out the desired data, for example:

var myDate = new Date();
// creates a new instance of the Date object 
using the current time and date on the user's computer
alert ("The date is " + myDate.getMonth() 
+ "-" + myDate.getDate() + "-" 
+ myDate.getFullYear());
// writes the month, day of the month, 
and four-digit year to the page

as shown in Figure 5-3.

Figure 5-3: Displaying month, day, and year.
Figure 5-3: Displaying month, day, and year.

6. USE ARRAYS

You can easily display the current date on your Web page using the methods of the Date object. To display the date in a particular format, another helpful object is the Array object.

An array is a collection of data. It can include text, numbers, or both. All Web programming languages include arrays. In JavaScript, you create an array by using the keyword new and Array(), for example:

var myArray = new Array();

This code creates an empty array.

Positions in an array are indexed, so you can refer to the data contained in any particular location in an array by using the index number in square brackets, such as:

var myValue = myArray[2];

Index values start at 0, not at 1, so the first position in the array is 0.

You can add a set of values to an array, for example:

myArray = [a,b,c];

This assigns a to the first position in the array, myArray[0], b to the second position, myArray[1], and c to the third position, myArray[2].

You can also assign array values individually, for example:

memberAges[5] = 52;

Array values don't need to be added in order. If you add only one value, the other values in the array are undefined. If you only assigned a value for the sixth position in memberAges, as in the previous line of code, the first five position values would be undefined.

7. 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>

8. CONVERT DATES TO STRINGS

If you want to create a custom format for displaying a date string, the easiest way to do so is to create a new Date object and get the individual pieces to put a string together, as in the previous examples. JavaScript also includes methods to create a string in a standard format, such as toString(), which returns the date as a string, for example:

var myTime = new Date ();
var newTime = myTime.toString();
document.write (newTime);

This displays the current date and time as a string, such as:

Sun Sep 14 03:06:30 MDT 2003

Another method is toUTCString(), which returns the date as a UTC string. If you change the above string to:

var newTime = myTime.toUTCString();

This displays the current date and time as a UTC string, such as:

Sun, 14 Sep 2003 09:06:30 UTC

9. INTERNATIONAL TIME

If your Web site has an international audience, you may want to use UTC for dates.

Important methods for international time include:

toLocaleString();

//returns date and time as a string based on local time

toUTCString();

//returns date and time as a string based on UTC time, as shown in the previous section

getTimezoneoffset();

//gives difference in minutes between local time and UTC time

For example, this code:

var now = new Date();
document.write (now.toLocaleString() + "<br>");
document.write(now.toUTCString() + "<br>");
document.write(now.getTimezoneOffset() + "<br>");

returns this output to the page:

Sunday, September 14, 2003 3:22:17 AM
Sun, 14 Sep 2003 09:22:17 UTC
360

You can use getTimezoneOffset() to determine the hours ahead or behind of UTC, for example:

var myTime = new Date ();
var zone = myTime.getTimezoneOffset();
zone = zone / 60;
if (zone < 0) {
var factor = "later";
}
else 
factor = "earlier";
document.write (myTime + " is " +  zone + 
" hours " + factor + " than UTC Time.");

returns this output to the page:

Sun Sep 14 03:42:47 MDT 2003 is 
6 hours earlier than UTC Time.

JavaScript includes methods for UTC time that are equivalent to the methods mentioned earlier in this lesson, such as:

setUTCDate();
setUTCFullYear();
getUTCDate();
getUTCFullYear();

and so on.

10. USE TIMERS

Timers can be used on a Web page to have a block of code execute after a specified amount of time. The easiest way to create a timer is with the setTimeout() method of the window object, for example:

setTimeout ("code to execute", milliseconds_delay);

The two parameters are:

  • the code that you want to execute when the timer fires
  • the time delay in milliseconds until the timer fires

So, how do you call a timer function? Most often, event handlers are used for this purpose, for example, onload to trigger a function when the page loads, or onclick to trigger a function when a button is clicked.

Event handlers are covered in detail in Lesson 6, but for now, the simplest way to do this is to use an onload event in the <body> tag and call a function that contains the timer.

First define the function in the head section of the page, for example:

<script type="text/javascript" language="JavaScript">
<!--
function startTime() {
timer = setTimeout('var tday = new Date();
alert ("Today is " + tday)',5000);
// sets a delay of 5000 milliseconds, or 5 seconds
}
// -->
</script>
</head>

then add an onload event to call the function:

<body onload = "startTime()">

You can also use a function name in place of the actual code in the setTimeout statement:

function startTime() {
var tday = new Date();
alert("Today is " + tday);
}
timer = setTimeout("startTime()",5000);

Moving On

In this lesson, you learned more about displaying date and time on a Web page. You also learned how to use arrays, and how to create a JavaScript timer. In Lesson 6, you'll learn about events, and how to use events to create image rollovers and dynamic text changes. Before you move on, don't forget to do the assignment and take the quiz. In addition, visit the Message Board to find out what your fellow students are up to.