Using JavaScript Variables and Built-In Functions, Part 3

By - thau!

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.

<title>The Book of JavaScript</title>
<script type = "text/javascript">
<!-- hide me from older browsers// get the Date object//

X var date = new Date();

// get the information out of the Date object
//var month = date.getMonth();
var day = date.getDate();
var year = date.getYear();
var hour = date.getHours();
var minutes = date.getMinutes();

Y month = month + 1;  // because January is month 0 
// fix the Y2K bug //

Z year = fixY2K(year);

// fix the minutes by adding a 0 in front if it's less than 10 
// [ minutes = fixTime(minutes);

// create the date string

// \ var date_string = month + "/" + day + "/" + year; 
] var time_string = hour + ":" + minutes; ^ 
var date_time_string = "Today is " + date_string + ".  The time is now " +

time_string + ".";

// This is the Y2K fixer function--don't worry about how this works,
// but if you want it in your scripts, you can cut and paste it.
//function fixY2K(number) {

if (number < 1000) {

number = number + 1900;}return number;


// This is the time fixer function--don't worry about how this works either. function fixTime(number) { if (number < 10) {

number = "0" + number;}return number;


// show me --></script></head><body>

_ <h1>Welcome to the Book of JavaScript Home Page!</h1>

<script type = "text/javascript">
<!-- hide me from older browsers

` document.write(date_time_string); 
// show me --> </script> </body> </html>
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 X up until Y 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 Xto 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:
  • Line Yadds 1 to the month because getMonth() thinks January is month 0.
  • Line Z fixes the Y2K problem discussed earlier in the chapter, in which the getYear() method returns the wrong thing on some older browsers. If you feed fixY2K() the year returned by date.getYear(), it will return the correct year. The fixY2K() function is not a built-in JavaScript function. I had to write it myself. Don't worry about how the function works right now. zLine [ fixes a minor formatting issue, using another function that's not built-in. If the script is called at 6 past the hour, date.getMinutes() returns 6. If you don't do something special with that 6, your time will look like 11:6 instead of 11:06. So fixTime() sticks a zero in front of a number if that number is less than 10. You can use fixTime() to fix the seconds too, for your homework assignment.

Getting the String Right

Now that we've made a few minor adjustments, it's time to build the strings. Line \ builds the string for the date. Here's the wrong way to do it:
var date_string = "month / day / year";
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 (+):
var date_string = month + "/" + day + "/" + year;
This may look a little funny at first, but it's done so frequently that you'll soon grow used to it. Line ] creates the string to represent the time. It is very similar to \. Line ^ puts \ and ]together to create the string that will be written to the website. Lines \ through ^ could all have been written as one long line:
var date_time_string = "Today is " + month + "/" + day + "/" + year + ". 
The time is now " + hour + ":" + minutes + ".";
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 ^ and _ 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 _ precedes the JavaScript that actually writes the date and time in `, 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.

How the European Space Agency Writes the Date to Its Page

The JavaScript used by the European Space Agency is very much like the code I used for the Book of JavaScript web page. One big difference between the two is that the ESA prints out the month using abbreviations like Jan and Feb for January and February. They do this using arrays, a topic discussed in Chapter 8, so in Figure 2-13 I've modified their code a bit to focus on topics covered so far.

This chapter is excerpted from The Book of JavaScript, 2nd Edition: A Practical Guide to Interactive Web Pages, from No Starch Press.

Page 2 of 2

Previous Page
1 2

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
Thanks for your registration, follow us on our social networks to keep up-to-date