reptile7's JavaScript blog
Sunday, April 17, 2005
The JavaScript Date object
Blog Entry #5

Most of the JavaScript objects that we'll be dealing with in the HTMLGoodies JavaScript primers and script tips are classified as "host objects". Host objects relate, directly or indirectly, to the document containing the script and the Web browser that 'hosts' and executes the document. Host objects are somewhat browser-dependent; those host objects that are recognized by both Internet Explorer and Netscape are helpfully diagrammed, through the courtesy of Netscape, at the Web Developer's Virtual Library. In addition and to a lesser extent, we will make use of JavaScript objects known as "core objects" (also variously called "native objects", "built-in objects", "intrinsic objects", or "fundamental objects") that are not browser-dependent but are an 'intrinsic' part of the language. A couple of blog entries ago, we discussed the JavaScript document object, which is obviously a host object. The 'star of the show' in HTMLGoodies' JavaScript Primers #3, which we begin to address today, is the core JavaScript Date object, which, through several associated methods, will allow you to extract date and time information from the clock running on your computer; this information can then be posted to a Web page by use of a document.write( ) statement. Later on in the HTMLGoodies primer series, we will also see the Date object used in scripts involving random numbers, statements, and images.

For most applications, JavaScript requires the Date object to be 'defined dynamically', i.e., a new 'instance' of a Date object must be created in order to make use of the methods available to it; this is accomplished by means of a constructor statement whose general syntax is shown in the primer as:

RightNow = new Date( );

This single, simple statement offers up a smorgasbord of new concepts for us to sink our teeth into. Let's take it from left to right, shall we?

(1) Although not identified as such in the primer, RightNow is a variable name. A variable in JavaScript is very much what it is in algebra: a symbol or 'placeholder' for a particular piece of information; in this case, RightNow will symbolize a new Date object. Variables crop up briefly at the end of Primer #3 in the "A known concern:" section, and are discussed more fully in Primer #6.

Formally, a variable in JavaScript is 'declared' with the statement "var", i.e.,

var RightNow = new Date( );

however, use of the var keyword, while 'good form', is not strictly necessary.

(2) The = character marks our introduction to JavaScript operators, a key part of the JavaScript syntax. An operator in JavaScript is very much what it is in mathematics or in other technical fields: "any of various mathematical or logical processes (as addition) of deriving one expression from others according to a rule", to borrow from Webster's New Collegiate Dictionary. In our constructor statement above, = is sort of an "equals sign" but more specifically functions as an assignment operator by which the right side of the equation is 'assigned' to the left side; in this case, a new Date object is assigned to the variable RightNow.

HTMLGoodies' treatment of JavaScript operators leaves a lot to be desired, to put it politely. There's no section on operators at the HTMLGoodies JavaScript keyword reference page; similarly and no less shamefully, operators never appear on the "Commands" lists on the "Click Here For What You've Learned" pages that appear at the end of the primers. Fortunately, however, DevGuru has posted a reasonably complete page of JavaScript operators, to which we'll be referring from time to time.

(3) The new keyword is also classified as an operator; its function in creating a new JavaScript object is self-explanatory.

(4) As noted above, Date is the new JavaScript object that we are creating. As a core object, Date is always capitalized; in contrast, host objects are not capitalized. The parentheses that follow Date in the constructor statement are again good form, syntaxwise, although leaving them out will not generate an error.

(5) Finally, the constructor statement ends with a semicolon. Semicolons in JavaScript are not operators but serve as statement delimiters; they are generally "optional [but are] required if you want to put more than one statement on a single line", to quote the folks at W3Schools. (FYI: notwithstanding its name, W3Schools is not connected to the World Wide Web Consortium (W3C).)

Q & A

Q: Are there any restrictions on what a variable name can be?

A: Yes. Conveniently located in the "Naming Variables" section of the MSDN JScript Variables page are some rules to which JavaScript variable names must conform. (One exception to these rules: variable names can definitely contain dollar signs ($$$).) On this topic, Joe states, "It [the variable name for the new Date object] doesn't matter as long as the object is given an original name that isn't found in JavaScript" - he is referring here to JavaScript's reserved words, which are equivalent to the reserved words and "future reserved words" of JScript.

Q: Does the new Date object have to be 'variabilized' in the first place?

A: No. The new Date( ) constructor can be directly acted on by a relevant method, for example:

<script language="javascript">
document.write("The current year is " + new Date( ).getFullYear( ) + ".")

The current year is 2005.

Using this formulation, the set of parentheses after Date is required, or you'll get an error. Like the script in the primer, this example shows that not only plain text and HTML but also JavaScript command statements themselves can appear in the write( ) parameter.

Q: Is the "new" keyword necessary? What happens if you leave it out?

A: There are in fact a couple of Date methods that do not require the creation of a new Date object, specifically, the parse( ) and UTC( ) methods; for example:

<script language="javascript">
var ms_since_1970 = Date.parse("January 1, 2006");

will output the number of milliseconds between January 1, 1970 and January 1, 2006:

In most cases, however, leaving out the new keyword will throw an error as soon as you attempt to act on Date (variabilized or not) with a method; contra the primer, a "static" Date is not created. On my computer, MSIE gives in this situation an "object doesn't support this property or method" run-time error, whereas Netscape gives a "Date_object.method( ) is not a function" error.

Q: What happens if Date is not capitalized?

A: A " 'date' is undefined" error pops up. Indeed, "date", with a lower-case "d", is an acceptable variable name for the Date object.

Q: Although Date is an object, the Date( ) syntax recalls that of the write( ) method. Does anything ever go in the parentheses that follow Date?

A: It's not necessary for the Date object to have parameters, obviously, but it can. Possible parameters for Date are listed at DevGuru's Date object page. Shown below are examples using the "dateString" and "yr_num, mo_num, day_num" parameters, respectively:

<script language="javascript">
var date = new Date("May 1, 2005");

Sun May 1 00:00:00 CDT 2005
(I live in New Orleans, where it is currently Central Daylight Time.)

<script language="javascript">
var d = new Date(2005, 0, 1);
document.write( d.getDay( ) );

(In JavaScript, January is indexed as 0, and not 1. January 1, 2005 was a Saturday, which is indexed as 6 by the getDay( ) method.)

So much for the constructor statement. We'll address other issues of the Primer #3 script when we pick up the conversation in the next entry.

var reptile7_

Comments: Post a Comment

<< Home

Powered by Blogger

Actually, reptile7's JavaScript blog is powered by Café La Llave. ;-)