Using the JavaScript Date Object
Since this is my first JavaScript blog post, I need to take a moment to recommend this book:
As far as I’m concerned, this is the JavaScript book to get. It explains the language at a level of detail that you simply won’t find reading online tutorials and samples. It covers everything from basic language syntax to AJAX. It has sections on regular expressions, XML, DOM scripting, and client-side graphics. It also has great reference sections for the various JavaScript objects: Date, Array, Number, etc. I am constantly referring to it whenever I’m programming in JavaScript.
Anyway, the purpose of this post is to show a couple of neat things that I discovered about the JavaScript Date object that aren’t readily apparent from most of the samples and tutorials that you’ll find. w3schools.com has a pretty good Date object reference if you need one.
One thing that you need to keep in mind when dealing with the JavaScript Date object is that the integer value for months is 0 based, not 1 based. This means that January = 0, February = 1, etc. For example, the following code:
var today = new Date(); // Creates a date object set to the current date and time alert( today.toDateString() + "\nMonth integer = " + today.getMonth());
Will show the following message:

What’s really cool about the JavaScript Date object is that it does date math for you. For example, we could set a date object to be January 1, 2009 and subtract 7 days from it:
var jan1_2009 = new Date(2009, 0, 1); // Creates a date object set to the January 1, 2009
var oneWeekBefore = new Date(2009, 0, 1 - 7); // Creates a date object set to the January 1, 2009 minus 7 days
alert("One week before " + jan1_2009.toDateString() + " is " + oneWeekBefore.toDateString());
var oneWeekBefore2 = new Date(2009, 0, 1); // Creates a date object set to the January 1, 2009
oneWeekBefore2.setDate( oneWeekBefore2.getDate() - 7); // Subtract 7 days
alert("One week before " + jan1_2009.toDateString() + " is " + oneWeekBefore.toDateString());
Both alerts in the code above would show the following:

You can also use the Date object to figure out how many days are in a given month. This is particularly useful for determining how many days are in February for a given year. When you create a Date object with a year, month, and a day of 0 then Date object automatically sets itself to the last day of the previous month. Remembering that month integers are zero based:
var day = new Date(2009, 2, 0); // Sets the date to the 0th day in March, which is the last day in February. alert(day.toDateString() + " : February of 2009 has " + day.getDate() + " days.");
This will display:

