Jump to content

Javascript Bug???


JonPixley

Recommended Posts

The parameter to the Date.setMonth function is zero-based:

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/setMonth

So 0 means January, 1 means February, 2 means March, etc.

 

Yeah, it's a little weird, but it's not a bug; it's just the way it's always worked in JavaScript. The reasons are historical and kind of complicated and you probably don't really want to know anyway.

Link to comment
Share on other sites

Okay, I did a little more research and found the answer here:

http://www.webdeveloper.com/forum/showpost.php?p=456670&postcount=2

 

Basically, because "new Date" creates a Date object initialized to the current date and time, the order in which you call setDate and setMonth on that object is significant.

 

So, depending on when you execute the code, this:

var TestDate = new Date;
TestDate.setYear(2009);
TestDate.setMonth(1); // 0 for January, 1 for February, etc.
TestDate.setDate(1);
return TestDate; // Sun Mar 01 2009...

is not the same as this:

var TestDate = new Date;
TestDate.setYear(2009);
TestDate.setDate(1);
TestDate.setMonth(1); // 0 for January, 1 for February, etc.
return TestDate; // Sun Feb 01 2009...

Specifically, for the first example, if you run this today (June 29th), your new Date object gets initialized to June 29th. Then you say, "change the month to February (1)." JavaScript says, okay, I'll do that, now it's February 29th, but that's not a valid date, so I'll consider that to be March 1st. Then you say, "change the date to the first," which it already is.

 

When you supply a year which does have a February 29th, it will work because the date is still valid after the call to setMonth. It will also work fine with any year if you wait a couple of days and try again, because the new Date object will be initialized to July 1st, and calling setMonth will change it to February 1st.

 

Yes, this is not exactly intuitive, but again, it's the way JavaScript has always worked, and there's really nothing we can do about it.

 

THE GOOD NEWS!

 

You can avoid this problem completely by setting all of the Date elements at once with the parameterized Date constructor:

var TestDate = new Date(2009, 1, 1);

(Again, the second parameter, the month, is zero-based, so the above returns February 1st.)

 

Another alternative is to use the Date.parse method, or the corresponding constructor:

var TestDate = new Date("Feb 1, 2009");

Please refer to the documentation for Date.parse for details.

 

Using (either form of) the constructor also has the advantage that the Date object is initialized to midnight of the date in question, instead of to the current time, which may help to avoid other subtle problems if you're doing date comparisons.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...