Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Lesson 12: Dates and Times

What's nice about writing JavaScript right to a Web page is all the stuff that already exists that you can grab and display.

This lesson talks about how you can display existing information using a new object, Date, and seven new methods: getDay(), getDate(), getMonth(), getYear(), getHours(), getMinutes(), and getSeconds().

Date is an object that contains the current day of the week, month, day of the month, current hour, current minute, current second, and current year. All that and looks, too, huh?

So, if Date has all that, why use any of the methods? Because you might not want all that stuff every time. What if you want only the day of the week? Then you use getDay() to extract just that day of the week from the Date object.

The Date and Time Methods

Even before beginning to delve into the sample script, let's discuss each of the Date object methods. They are quirky to say the least.

First, all seven methods return numbers rather than text. It would be nice if getDay() would give you Monday, or Wednesday, or Saturday, but it doesn't. It gives you a number between 0 and 6.

Between 0 and 6?

Yes. Allow me to introduce you to one of the more frustrating aspects of JavaScript.

JavaScript counts start at 0. The number 0 is equal to the first element of a list in JavaScript's mind.

The common week starts on Sunday and ends on Saturday. You might see it differently, but JavaScript sees the seven-day week as Sunday through Saturday. Those seven days are in JavaScript's mind as being numbered from 0 (Sunday) through 6 (Saturday).

So, if you call for getDay() and it's Wednesday, you will actually get only the number 3 returned. Goofy, yes, but that's what happens.

But so what? The previous script doesn't call for the day of the week. True, but it does call for the month. JavaScript counts that up from 0, too. Thus, the number returned for the month is always one less than you would expect.

The Methods and What They Return

Here's a quick rundown of each method and what it returns. It'll help you to understand what pops up on your page when using the variable, as I'll show:

  • getDate()—Believe it or not, this one acts normally. It returns the day of the month as the correctly numbered day of the month.

  • getDay()—Returns the numbers 0 (Sunday) through 6 (Saturday), depending on the day of the week.

  • getHours()—Returns the hour of the day in a 24-hour format counting the hours up from 0 through 23.

  • getMinutes()—Returns the minute of the hours counting up from 0 up through 59, but this one isn't bad. There actually is a 0 at the top of the hour, so we're good to go with getMinutes.

  • getMonth()—Returns the month of the year counting up from 0. The month of February therefore returns the number 1.

  • getSeconds()—Returns the second of the minute counting up from 0 to 59. This method, like getMinutes, is okay in that there is actually a 0 at the top of the hour.

  • getFullYear()—Returns the 4-digit year. JavaScript ran into a little trouble when the Y2K bug hit. The original year command, getYear(), returned only a two-digit year. When it was 1999, that was okay. But when 2000 began, instead of returning 00, the command returned 100. Oops. Do yourself a favor and start using getFullYear() exclusively. It's a quick fix that works pretty well.

The Sample Script

Take a look at this lesson's script:

<SCRIPT LANGUAGE="JavaScript">
//This script posts the exact day and time you arrived
RightNow = new Date();
document.write("Today's date is " + RightNow.getMonth()+ "-")
document.write("+ RightNow.getDate() + "-" + RightNow.getFullYear() + ".")
document.write("You entered this Web Page at exactly: "
 + RightNow.getHours() + "hours")
document.write("+ RightNow.getMinutes() + " minutes and "
 + RightNow.getSeconds() + " seconds")
</SCRIPT>

The script displays the date and time the page was loaded with this script, as shown in Figure 3.3.

Figure 3.3 The date and time methods display a variety of useful information.

Click Here!

To see this script's effect on your computer, click Lesson Eleven Effect in your download packet, or see it online at http://www.htmlgoodies.com/JSBook/lesson12effect.html.

Wait! What's That // Thing?

You are an observant one, aren't you? That double slash denotes a single comment line inside the script. It means that the text that follows will not be used in the process, but rather will just be reprinted as is. It works just like the multiline comment you saw in Lesson 11, earlier in this chapter. You can add as many of them as you want, as long as each line starts with the double slash.

You also can use the double slashes at the end of a line of JavaScript to remind yourself, or tell your users, what the line of JavaScript will do. Here's an example:

document.write("text") //This writes text to the page

Deconstructing the Script

If you look at the sample script, you'll see that the effect is created by asking the script to write the month, date, year, hour, minute, and second to the page. The extra verbiage stuck in there just makes it obvious what you're looking at.

Let's start with the first one called for in the preceding script—the month—and then we can start to break down how this works. As stated before, getMonth() is a method. That said, we now must concern ourselves with what object getMonth() is a method of.

It might appear from the script that getSomething() is a method of document. Not so—the method of document is write. getMonth() is actually a method of the object Date. Look up at the script and you'll see that Date is set aside in the command:

RightNow = new Date();

What is happening here is we are setting aside the object for the method getMonth() to work on. Actually, we're creating a new Date object to work with in the script.

Date, remember, contains all the date and time information you'll need. In fact, when you use one of the getSomething() methods, you're simply extracting one section of what Date possesses.

I'll prove that to you. Here's code that uses only the Date object without any method:

<SCRIPT LANGUAGE="javascript">
document.write("Here's some information: " +Date()+ ".")
</SCRIPT>

With just that, look at Figure 3.4 to see all the good stuff you get.

Figure 3.4 Using the Date object yields a lot of information.

Defining a Variable for the Date Object

The variable name given to the Date object in the sample script is RightNow. Now, I could have called it Zork or Fred, for all the browser cares. It doesn't matter as long as the object is given an original name that isn't found in JavaScript. See Appendix C for a list of unusable words.

If that seems backwards to you, it does to me, too. It seems like it should be new Date = RightNow, but it isn't. You're learning a new language, and you have to play by its rules.

The earlier command is saying this: RightNow is the variable that represents a new Date();.

But why "new" Date? The date has to be new so that you get a new date every time the page is entered or reloaded. Without the new command, the date would remain static. You reinforce the fact that the date has to be new by giving it a variable name, too.

Hooray! You have your object variable name set so that your getMonth() method can act on it. You want this month to be printed on the page, so you need to have a document.write() statement in there somewhere. You also know that what appears in the parentheses is printed on the page, so put together a smaller version of the big script in this lesson by following a logical process:

  1. You need to place the <SCRIPT LANGUAGE="javascript"> first.

  2. Then, insert a comment line that tells what this thing does.

  3. You'll need to create a new Date object before you can call on the getMonth() portion, so insert that. Make sure the call ends with a semicolon.

  4. Now you can place the document.write() statement.

  5. Inside the document.write's incidence, follow the same format as in Lesson 1 in Chapter 1, "The Basics."

  6. Text that is to be printed must be inside double quotation marks.

  7. Finish up with </SCRIPT>.

Here's what you get:

<SCRIPT LANGUAGE="javascript">
//This script will post the name of the month
RightNow = new Date();
document.write("This is the month " + RightNow.getMonth ".")
</SCRIPT>

Look at the full script again. That long line of text doesn't look so tough now. It's simply the RightNow object variable name followed by the next getSomething() method. I separated each with a hyphen; remember the hyphen is to be printed so it must be in quotation marks.

Building the Lines of document.write Code

I won't go through it all because you probably have the swing of it by now, so I'll discuss just the date portion of the script. It looks like this:

document.write("Today's date is " + RightNow.getMonth()+ "-")
document.write(+ RightNow.getDate() + "-" + RightNow.getYear() + ".")
  • It starts with "Today's date is ", with a space at the end for continuity.

  • The plus sign is next.

  • RightNow.getMonth() is added without quotation marks because we do not want that printed—we want the number returned.

  • Another plus sign follows.

  • Now, a hyphen appears in quotation marks to separate it from the next number. No space is used because we want the next number to butt right up against it.

  • Next comes a plus sign.

  • Then comes the next document.write statement.

  • It starts with a plus sign because the first item in this statement is a return.

  • Now RightNow.getDate is added because we want the number of the day (no quotation marks).

  • A plus sign is next.

  • Another hyphen appears in quotation marks so it is printed right to the page.

  • Another plus sign is next.

  • Last is another new method, RightNow.getYear, which returns the number of the year.

Just continue to follow this same format, and the script will print out what you tell it to. So now you can tell everyone what time it is. But as Chicago sang, "Does anybody really know what time it is? Does anybody really care?"

Wait! What About Some of the Numbers Being One Off?

It's actually pretty easy to fix. So far, you've seen the plus sign used to surround text so that it acts as a return rather than printing to the page.

That plus sign can also act as a, well, as a plus sign intended to add things together. We'll get more into the mathematics of JavaScript in Chapter 5, "Forms: A Great Way to Interact with Your Users," but for now, let's just do some simple addition.

To get the returns from getDay(), getMonth(), and getSeconds() to display correctly, you must add a couple of steps to the process.

To return the correct number, you need to return each of the method.objects (listed earlier) and assign each a variable name.

Also, when you assign a variable name, you must add 1. Here's an example of a script that returns the date in ##/##/#### format:

<SCRIPT LANGUAGE="javascript">
RightNow = new Date();
var dy = RightNow.getDate() + 1
var mth = RightNow.getMonth() + 1
var yr = RightNow.getFullYear()
document.write(+ dy + "/" + mth + "/" + yr + ".")
</SCRIPT>

See the format? I assigned the variable name dy to the code that would return the number representing the day of the week and added 1. Then, in the document.write statement, I called only for the variable name dy. That returns the number returned by RightNow.getDay() plus 1.

Now it's correct.

I did the same for RightNow.getMonth(). The command getFullYear() returns the entire four-digit year.

Your Assignment

This one isn't so tough:

  • Write a script that asks for the user's name through a prompt.

  • Use that name to write a piece of text that reads Welcome user-name. It is minutes past hour. Thanks for coming.

  • Now, here's the kicker: Make that text appear in an alert that pops up when the page loads.

  • Bonus points are available if you call for the minutes and hours by using variable names.

Click Here!

You can see a possible answer on your own computer by clicking Lesson Twelve Assignment in your download packet, or see it online at http://www.htmlgoodies.com/JSBook/ assignment12.html.

  • + Share This
  • 🔖 Save To Your Account