Page 1 of 1

Javascript date mystery

Posted: Tue Nov 04, 2008 5:47 am
by Eric Praline
~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


Hi peeps

I've just come across a problem with the Javascript date object, and I'm not sure if it's me or something up with Javascript itself!

I have a site to manage book loans. One page shows the date a book is due back, with a button that renews the loan by adding 7 days to the current date (calling a Javascript function via onClick). I thought everything was working fine, but the other day I came across a problem when I renewed a book on 31st October...
So, I wrote a little test function, which looks like this...

Code: Select all

function addSevenDays() {
    var duedate = new Date;
    duedate.setDate(31); // 31st
    duedate.setMonth(9); // October (Javascript counts month values 0-11)
    duedate.setFullYear(2008); // 2008
    
    var plusSeven = new Date(duedate.getTime() + 7*24*60*60*1000); // add 7 days
    document.forms["test"]["newDateValue"].value = plusSeven;
}
And the value I got was "Wed Oct 08 2008 11:36:17 GMT+0100 (GMT Standard Time)". Umm, no - it should actually be "Fri Nov 07 2008...".
If I change the value to 30th October it works it out perfectly - and having tried my function on all months with 31 days there appears to be a slight hiccup in date calculation... so, am I doing something wrong, or if not and it's a known Javascript problem, what can I do about it?


~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.

Re: Javascript date mystery

Posted: Tue Nov 04, 2008 6:05 am
by VladSun
Your set*() call order is wrong ;) I think, you already know why :)

Re: Javascript date mystery

Posted: Wed Nov 05, 2008 4:09 am
by Eric Praline
A-ha! I see it now - you have to set dates in Year-Month-Day order... which seems very pedantic of Javascript that it doesn't work correctly if you set dates in the 'wrong' order!

Cheers mate :D

Re: Javascript date mystery

Posted: Wed Nov 05, 2008 8:23 am
by VladSun
It's not pedantic at all ;)

Check this out:
[js]var duedate = new Date;alert(duedate);duedate.setDate(31); // 31stalert(duedate);duedate.setMonth(9); // October (Javascript counts month values 0-11)duedate.setFullYear(2008); // 2008 alert(duedate);[/js]

It's the new Date() which will automatically hold the current date and time as its initial value.
And November has 30 days, not 31.

It would have been a lot easier, if you used
[js]var duedate = new Date();duedate.setFullYear(2008, 9, 31); // 2008-10-31[/js]

;)