Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript getDay returning incorrect values for April, June, September, November

Tags:

javascript

I'm using this script located here: http://www.javascriptkit.com/script/script2/dyndateselector.shtml

If you try it, and go to any of April, June, September or November, you will notice that the day of the week columns are incorrect. Here's a list of incorrect data (the x starts y stuff is showing the following month.)

Bugged months: 4/April (starts Sunday instead of Friday) May starts Sunday

6/June (starts Friday instead of Wednesday) July starts Friday

9/September (starts Saturday instead of Thursday) October starts Saturday

11/November (starts Thursday instead of Tuesday) December starts Thursday

You'll notice that every bugged month is starting with the day of the following month, yet all the other months seem to be correct.

I can't find anything on this problem. Anyone able to help? The actual Javascript alone can be found here, and the getDay() method occurs on line 125: http://pastebin.com/0zuBYrzv

I've tested in both Firefox and Chrome.

Here's some very simple code to demonstrate the issue:

<script>
var d = new Date();
d.setMonth(5);
d.setFullYear(2011);
d.setDate(1);
alert(d.getDay());
</script>

This will create an alert with the message "5", meaning Friday (5+1 = 6, Friday is the 6th day of the week,) when in fact Wednesday is the start of the week.

like image 489
John M. Avatar asked May 31 '11 18:05

John M.


2 Answers

This is actually pretty interesting as i am guessing that tomorrow your original code will work as you want again.

What i think is happening is you are creating a new Date and that will automaticly initialize to today (31th of may). Then you set the Month to June by which you basically say make it 31th of June. This date doesn't exist so javascript will turn it into 1th of July. Finally you set the Date but since your month is not anymore what you want it to be the results will be wrong.

like image 129
Jan-Peter Vos Avatar answered Sep 21 '22 15:09

Jan-Peter Vos


Looks like 0 is january and 11 is december.

like image 34
kennebec Avatar answered Sep 20 '22 15:09

kennebec