Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The fifteenth of February isn't found

I'm in javascript, running this in the console

d = new Date();             
d.setMonth(1);
d.setFullYear(2009);
d.setDate(15);                                  
d.toString();

outputs this:

"Sun Mar 15 2009 18:05:46 GMT-0400 (EDT)"

Why would this be happening? It seems like a browser bug.

like image 337
Issac Kelly Avatar asked Oct 30 '08 22:10

Issac Kelly


1 Answers

That's because when you initialize a new Date, it comes with today's date, so today is Oct 30 2008, then you set the month to February, so there is no February 30, so set first the day, then the month, and then the year:

d = new Date();
d.setDate(15);                    
d.setMonth(1);
d.setFullYear(2009);   

But as @Jason W, says it's better to use the Date constructor:

new Date(year, month, date [, hour, minute, second, millisecond ]);
like image 167
Christian C. Salvadó Avatar answered Sep 28 '22 01:09

Christian C. Salvadó