Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: date depending on the field specification order? Really?

Tags:

javascript

Why on earth does this code:

var a = new Date();                             
var b = new Date();     

a.setDate(31);
a.setMonth(11);
a.setFullYear(2009);

b.setFullYear(2009);
b.setMonth(11);
b.setDate(31);

ouputs correctly 31 december 2009 for b and 3 december 2009 :-O for a? Not in browser MyHorribleScrap version 6.6.6 but BOTH on FF 3.6 AND IE 8.06.6001

like image 276
Daniel Avatar asked Feb 26 '10 15:02

Daniel


1 Answers

That's why is recommended to use the Date constructor with arguments.

What is happening is when you instantiate the Date object, it gets the current date (today, February 26), and February has only 28 days, when you set the date by setDate(31), it jumps to the March 3.

The recommended way:

var a = new Date(2009, 11, 31);
// new Date(year, month, date [, hour, minute, second, millisecond ]);
like image 90
Christian C. Salvadó Avatar answered Oct 17 '22 19:10

Christian C. Salvadó