开发者

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

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


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 ]);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜