PDA

View Full Version : javascript bug....



Vermelh0
07-31-2002, 11:34 PM
I've been pouring hours into a script, wondering why it was no longer working and then I figured "wait a minute, maybe it's not my fault." And guess what, it isn't. I think I've been able to isolate the bug, but why does it happen? The problem is with the IE's date object and todays date 2002-07-31. The set/get month functions go haywire and do not return proper values.
Here's a sample function:

function doanything()
{
today = new Date(2002, 07, 31, 0, 0, 0);
today.setMonth(10);
alert(today.getDate()+'/'+(today.getMonth()+1)+'/'+today.getFullYear());
today.setMonth(9);
alert(today.getDate()+'/'+(today.getMonth()+1)+'/'+today.getFullYear());
}

The first alert box returns 1-12-2002 and the second 1-10-2002.
As you can see the first date is off by one..... If I initialize the date to another date say 2002-07-30, the problem goes away.
Hum... My head hursts..... What others bugs should I be on the lookout on IE?
V

boywonder
08-01-2002, 03:21 AM
Your original date is july 31...
you set the month to november, but since there's no November 31, it rolls to December 1. (1-12-2002)
Then you set that date's month to October so it returns 1-10-2002.

BrainJar
08-01-2002, 05:04 PM
That's how the Date object is designed to work.

You might find this article useful: http://www.brainjar.com/js/calendar/. It explains how you can add custom methods to the Date object to add or subtract days, months and years.

Vermelh0
08-01-2002, 10:25 PM
Oh, I see...
That logic seems counterintuitive though... I understand that happening with days. For instance, if you're on the first, and your set the the number of days to +32, then I would expect a rollover. But to do that on the months seems... wrong...
Ok, thanks alot for your help...
I was panicking for a while there... :)
V

Roy Sinclair
08-01-2002, 10:52 PM
Originally posted by Vermelh0
Oh, I see...
That logic seems counterintuitive though... I understand that happening with days. For instance, if you're on the first, and your set the the number of days to +32, then I would expect a rollover. But to do that on the months seems... wrong...
Ok, thanks alot for your help...
I was panicking for a while there... :)
V

Think of it this way, the date field will always contain a valid date. Setting one part of the date field to something that would cause another part to be invalid will cause the invalid part to be "adjusted".