Home > Articles

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020