time - Javascript Date() converts 29Feb2012 to 1Mar2012 - Stack Overflow

This is my code:var d = new Date();var date = 29;var month = 1;Febvar year = 2012;Bissextile

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742318870a4421397.html

相关推荐

  • time - Javascript Date() converts 29Feb2012 to 1Mar2012 - Stack Overflow

    This is my code:var d = new Date();var date = 29;var month = 1;Febvar year = 2012;Bissextile

    11小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信