Sunday, April 17, 2005
Blog Entry #5
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?
var RightNow = new Date( );
however, use of the var keyword, while 'good form', is not strictly necessary.
Q & A
Q: Are there any restrictions on what a variable name can be?
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:
document.write("The current year is " + new Date( ).getFullYear( ) + ".")
The current year is 2005.
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:
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:
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.)
var d = new Date(2005, 0, 1);
document.write( d.getDay( ) );
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.