Using Variables and Built-in Functions to Update Your Web Pages Automatically - Page 5 | WebReference

Using Variables and Built-in Functions to Update Your Web Pages Automatically - Page 5


[previous]

Using Variables and Built-in Functions to Update Your Web Pages Automatically

Writing the Date to Your Web Page

Now that you know about variables and functions, you can print the date to your web page. To do so, you must first ask JavaScript to check the local time on your visitor's computer clock:

The first part of this line, var now =, should look familiar. It sets the variable now to some value. The second part, new Date(), is new; it creates an object.

Objects store data that require multiple pieces of information, such as a particular moment in time. For example, in JavaScript you need an object to describe 2:30 PM on Saturday, January 7, 2006, in San Francisco. That's because it requires many different bits of information: the time, day, month, date, and year, as well as some representation (in relation to Greenwich Mean Time) of the user's local time. As you can imagine, working with an object is a bit more complicated than working with just a number or a string.

Because dates are so rich in information, JavaScript has a built-in Date object to contain those details. When you want the user's current date and time, you use new Date() to tell JavaScript to create a Date object with all the correct information.

Note: You must capitalize the letter D in Date to tell JavaScript you want to use the built-in Date object. If you don't capitalize it, JavaScript won't know what kind of object you're trying to create, and you'll get an error message.

Built-in Date Functions

Now that JavaScript has created your Date object, let's extract information from it using JavaScript's built-in date functions. To extract the current year, use the Date object's getYear() function:

Date and Time Methods

In the code above, the variable now is a Date object, and the function getYear() is a method of the Date object. Methods are simply functions that are built in to objects. For example, the getYear() function is built in to the Date object and gets the object's year. Because the function is part of the Date object, it is called a method. To use the getYear() method to get the year of the date stored in the variable now, you would write:

Table 2-1 lists commonly used date methods. (You can find a complete list of date methods in Appendix C.)

Table 2-1: Commonly Used Date and Time Methods

Name Description
getDate() The day of the month as an integer from 1 to 31
getDay() The day of the week as an integer where 0 is Sunday and 1 is Monday
getHours() The hour as an integer between 0 and 23
getMinutes() The minutes as an integer between 0 and 59
getMonth() The month as an integer between 0 and 11 where 0 is January and 11 is December
getSeconds() The seconds as an integer between 0 and 59
getTime() The current time in milliseconds where 0 is January 1, 1970, 00:00:00
getYear() The year, but this format differs from browser to browser

Note: Notice that getMonth() returns a number between 0 and 11; if you want to show the month to your site's visitors, to be user-friendly you should add 1 to the month after using getMonth() as shown in line 16 in Figure 2-12.

Internet Explorer and various versions of Netscape deal with years in different and strange ways:

  • Some versions of Netscape, such as Netscape 4.0 for the Mac, always return the current year minus 1900. So if it's the year 2010, getYear() returns 110.
  • Other versions of Netscape return the full four-digit year except when the year is in the twentieth century, in which case they return just the last two digits.
  • Netscape 2.0 can't deal with dates before 1970 at all. Any date before January 1, 1970 is stored as December 31, 1969.
  • In Internet Explorer, getYear() returns the full four-digit year if the year is after 1999 or before 1900. If the year is between 1900 and 1999, it returns the last two digits.

You'd figure a language created in 1995 wouldn't have the Y2K problem, but the ways of software developers are strange. Later in this chapter I'll show you how to fix this bug.

Code for Writing the Date and Time

Now let's put this all together. To get the day, month, and year, we use the getDate(), getMonth(), and getYear() methods. To get the hour and the minutes, we use getHours() and getMinutes().

Figure 2-12 shows you the complete code for writing the date and time (without seconds) to a web page, as seen on the Book of JavaScript home page.

Figure 2-12: Writing the current date and time to a web page

Line-by-Line Analysis of Figure 2-12

Here are a few interesting things in this example.

Getting the Date and Time

The lines from 7 up until 16 get the current date and time from the visitor's computer clock and then use the appropriate date methods to extract the day, month, year, hours and minutes. Although I'm using a variable name date in line 7 to store the date, I could have used any variable name there: the_date, this_moment, the_present, or any valid variable name. Don't be fooled into thinking that a variable needs to have the same name as the corresponding JavaScript object; in this case, date just seems like a good name.

Making Minor Adjustments

Before building the strings we will write to the website, we need to make some little adjustments to the date information just collected. Here's how it works:

Getting the String Right

Now that we've made a few minor adjustments, it's time to build the strings. Line 27 builds the string for the date. Here's the wrong way to do it:

If you wrote your code this way, you'd get a line that says Today is month / day / year. Why? Remember that JavaScript doesn't look up variables if they're inside quotes. So place the variables outside the quote marks and glue everything together using plus signs (+):

This may look a little funny at first, but it's done so frequently that you'll soon grow used to it. Line 28 creates the string to represent the time. It is very similar to line 27. Line 29 puts line 27 and line 28 together to create the string that will be written to the website. Lines 27 through 29 could all have been written as one long line:

However, using three lines makes the code easier for people to read and understand. It's always best to write your code as if other people are going to read it.

What Are Those Other Functions?

The JavaScript between lines 29 and 53 defines the fixY2K() and fixTime() functions. Again, don't worry about these lines for now. We'll cover how to write your own functions in glorious detail in Chapter 6.

JavaScript and HTML

Make sure to place your JavaScript and HTML in the proper order. In Figure 2-12, the welcoming HTML in line 53 precedes the JavaScript that actually writes the date and time in line 57, since the browser first writes that text and then executes the JavaScript. With JavaScript, as with HTML, browsers read from the top of the page down. I've put document.write() in the body so that the actual date information will come after the welcome text. I've put the rest of the JavaScript at the head of the page to keep the body HTML cleaner.

Why document.write()?

Notice that the code in Figure 2-11 uses document.write() instead of window.document.write(). In general, it's fine to drop the word window and the first dot before the word document. In future chapters I'll tell you when the word window must be added.

This chapter is excerpted from the book titled, The Book of JavaScript, 2nd Edition, authored by thau!. Copyright 2006 No Starch Press, December, 2006.

[previous]

URL: