admin管理员组

文章数量:1332361

This is my code:

var d = new Date();
var date = 29;
var month = 1; // Feb
var year = 2012; // Bissextile year
d.setUTCDate(date);
d.setUTCMonth(month);
d.setUTCFullYear(year);
d.setUTCHours(0);
d.setUTCMinutes(0);
d.setUTCSeconds(0);
document.write(d.getUTCDate()+"<br />"+d.getUTCMonth()+"<br />"+d);

This is the result in Firefox:

1
2
Thu Mar 01 2012 11:00:00 GMT+1100 (AUS Eastern Standard Time)

When the value of date is 28:

28
1
Tue Feb 28 2012 11:00:00 GMT+1100 (AUS Eastern Standard Time)

There is no Wednesday!

Is it an error of JS or there is another method to find Wed Feb 29 2012 here?

This is my code:

var d = new Date();
var date = 29;
var month = 1; // Feb
var year = 2012; // Bissextile year
d.setUTCDate(date);
d.setUTCMonth(month);
d.setUTCFullYear(year);
d.setUTCHours(0);
d.setUTCMinutes(0);
d.setUTCSeconds(0);
document.write(d.getUTCDate()+"<br />"+d.getUTCMonth()+"<br />"+d);

This is the result in Firefox:

1
2
Thu Mar 01 2012 11:00:00 GMT+1100 (AUS Eastern Standard Time)

When the value of date is 28:

28
1
Tue Feb 28 2012 11:00:00 GMT+1100 (AUS Eastern Standard Time)

There is no Wednesday!

Is it an error of JS or there is another method to find Wed Feb 29 2012 here?

Share Improve this question asked Mar 5, 2014 at 13:26 KaiKai 1551 gold badge2 silver badges13 bronze badges 1
  • it's not a bug, it's a feature – Sergio Commented Mar 5, 2014 at 13:47
Add a ment  | 

1 Answer 1

Reset to default 10

The problem is the order in which you are setting the items.

You're starting from today, which is March 5th, 2014.

You are then setting the date to 29. Result: March 29th, 2014.

Then you set the month to 1. Result: Feburary 29th, 2014. Oh wait, that's wrong because 2014 is not a leap year, so JS corrects it to March 1st, 2014.

Finally, you set the year. Final result is March 1st, 2012.

Try setting the year first, then the day, then the month.

Alternatively, use the constructor properly: new Date(2012,1,29) should work just fine.

本文标签: timeJavascript Date() converts 29Feb2012 to 1Mar2012Stack Overflow