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
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
Share Improve this question edited Feb 26, 2010 at 15:18 Dominic Rodger 99.9k37 gold badges203 silver badges217 bronze badges asked Feb 26, 2010 at 15:12 DanielDaniel 1,3572 gold badges19 silver badges39 bronze badges 1- What on earth is MyHorribleScrap? – Justin Morgan Commented Feb 11, 2013 at 18:17
2 Answers
Reset to default 14That's why is remended 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 remended way:
var a = new Date(2009, 11, 31);
// new Date(year, month, date [, hour, minute, second, millisecond ]);
i was practicly writing Tim´s answer =/
First set the year(because it could be a leap year) , then the month, and finally de date, but the best practice is using the constructor Date(year,month,date) but not always want to do that way.