Wednesday, October 31, 2007

JavaScript Date Object Tip

Quicktip: Nov. 31, 2007 == Dec. 1, 2007

Background
I had to repair a JavaScript based calendar popup tool today. For some reason November was not being displayed correctly. It had the correct number of days but November 1st was on Saturday, not Thursday.

This issue only manifested itself when the current date is the 31st day of the month and only caused display problem for months with less than 31 days.

What is going on?
This issue turned out to be related to an odd behavior of the JavaScript date object so I thought I'd share.

Let's go over the "offending" code:

var today = new Date(); // new Date(2007, 9, 31);
This creates a new date object with Oct. 31, 2007 (which is today)

today.setMonth(10);
This sets the month to November

alert(today);
This shows an alert box with Dec 1, 2007

But wait!! Didn't we set the month to November? Well, we did, but November only has 30 days. October had 31 days. So I guess we set the date to be Nov. 31. You could say that Nov. 31 is the same as Dec. 1. You might not say that but JavaScript does.


Solution(s):
1. Set the day of the month before setting the month.
2. Create a new date object using appropriate parameters: new Date(2007, 10, 1);

2 comments:

  1. Actually the setMonth function is a 0 based array, so setMonth(11) actually tells it to set it to December. If you want to set it to November, you have to use setMonth(10). Yes, it's not exactly intuitive.

    p.s. Love the uploader

    ReplyDelete
  2. Thanks.
    I fixed that.

    ReplyDelete