JavaScript – Date Manipulation Made Easy

Date objects seem very counterintuitive on first encounter. But they’re really quite easy

to understand. So let’s clear away the cobwebs once and for all.

The first thing to get straight is that a Date object can either be a string or a number

depending on context. This is in the spirit of all things JavaScript: a data type can be

whatever it’s supposed to be under the circumstances. Type conversions are done dynamically,

in the background, so you don’t have to worry about explicit type casts or things that might

get you in trouble with the Type Police if you’re in the wrong place at the wrong time.

But JavaScript always lets you coerce the context in whatever direction you want. If you

want something to act like a string, all you have to do is append toString() to the

object, whatever it is (even if it’s, say, a Function). Equivalently, you can shroud the

target (whatever it may be) in a String() call. Likewise, to make something behave like a

Number, all you have to do is shroud it with Number(). Or make the context numerical, by

multiplying by unity, or adding zero.


var n = '653';
n = n.substr(0,2); // 'n' is now 65
n *= 2; // 'n' is now 130
n = Number(n) + Number('100'); // 'n' is 230
n /= 100; // 'n' becomes 2.3
n = String(n) + String('456'); // 'n' is 2.3456

If you’ve been following all this so far, you should have no trouble guessing what the

outcome of the code shown below would be:


n = '120';
var result = n.substr(0,2) * 1 + 3;

In most languages, the result of this kind of code would be a runtime error involving NaN

(‘not a number’), because most languages won’t let you multiply a string by a number, then

add 3 to it. In JavaScript, ‘result’ is a number, value 15.

If you understand all of this, Dates become much simpler.

A Date object is a number if you wrap it with Number() or a string if you wrap it with

String().

As a number, a newly created Date represents the number of milliseconds since Jan. 1,

1970.

For fun, I suggest you try the following code:

app.alert(new Date);

If you execute this code, you should see an alert dialog that displays something like

Fri Feb 25 20:22:11 2000

You can assign this ‘new Date’ directly to a field value:

// new Date() will be resolved as a string by default:
this.getField('mydate').value = new Date;

Note that parens are optional on Date.

If you would rather chop the day of the week off the front, just do:

this.getField('mydate').value = (new Date()).toString().slice(4);

which gives:

     Feb 25 20:22:11 2000 

or if you don’t want hours:min:secs, do


this.getField('mydate').value =
(new Date()).toString().substr(4,7)+
(new Date()).toString().substr(21,4);

which gives

   Feb 25 2000

etc.

Split-Second Timing

Since a Date is (numerically speaking) just a raw millisecond count, you can easily

compare dates using greater-than, less-than, or equality operations, and Date arithmetic

becomes quite natural. If you want to tell your user how long he has kept a form open, for

example, just include a line of code as a Page Open action, stuffing ‘new Date’ into a

global, then call ‘new Date’ again later and subtract the original (page open) value to get

the elapsed milliseconds. Convert the result to seconds by dividing by 1000; to minutes by

dividing by 60 * 1000; hours, divide by 60 * 60 * 1000; etc.

As for getting the raw millisecond value of a future date, just try:


var AprilFools = Number(new Date('Apr 1 2000')); // value 954565200000

Subtracting a future date from the present date forces both dates to behave like numbers,

and the result of the subtraction is a negative number. Conversely, subtracting an older

date from a newer one yields a positive number.

Convenience Functions, So-Called

The Date object comes with a huge number of built-in convenience methods (too huge to

list here, so I suggest you consult one of the JavaScript books mentioned in the book links

below, particularly Flanagan’s book, pp. 447-466). There are methods like getHours()

to extract just the hour portion of a Date object, getDay() to return the day of the

week, toGMTString(), to convert a date to Greenwich time (which is now properly

called Universal Coordinated Time, abbreviated UTC for some strange reason),

getTimeZoneOffset(), and much more.

Unfortunately, none of these methods helps with converting a time interval (the

difference between two Dates) to hours, days, minutes, etc. To do that, you have to get the

raw millisecond value of the interval and start dividing by 1000, 60, 60 * 60, etc.

What’s even more unfortunate is that the foregoing ‘convenience’ methods actually return

raw numbers, not days of the week, month names, etc. For example, getDay() is

supposed to return the day of the week. It actually returns 4 for Thursday, 5 for Friday,

etc. Likewise, April isn’t April. It’s 4. (What would you expect from the European Computer

Manufacturers Association? You didn’t really think ECMA would let English names for days of

the week, etc., creep into the JavaScript standard, did you?)

Judging from the ancient mechanical device on my wrist, it’s time to go.

You May Also Like

About the Author: Kas Thomas

Leave a Reply