JavaScript setDate返回错误的日期 [英] JavaScript setDate returning wrong dates

查看:109
本文介绍了JavaScript setDate返回错误的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从字符串中获取日期,解析它以获取日期,月份和年份的对象,并将其用于实例Date对象。



我试图实现的是将日期增加一天。
一切正常,除了setDate方法坚持要求我无效日期有时...



例如,如果我添加1天到2月28日2011年2月29日将返回我2011年2月29日...实际上不存在的日期。



这是JavaScript本机日期/时间API的错误/限制还是我只是做错了?我觉得很难相信它的行为方式没有检查日期的有效性。

  var myDate = new Date(2011 ,2,28); 
alert(myDate);
myDate.setDate(myDate.getDate()+ 1);
alert(myDate); // 2011年2月29日

谢谢。

解决方案

你不在2月 - 2月是3月3日

JS月份是0根据

  var myDate = new Date(2011,1,28); // 2月28日
alert(myDate);
myDate.setDate(myDate.getDate()+ 1);
alert(myDate); // 2011年3月1日!

PS:如果您创建日期使用 var d = new Date()并且不要在小时内通过执行 d.setHours(0,0,0,0)之后


I'm getting a date from a string, parsing it to get the day, month and year constituants and use these to instance a Date object.

What I am trying to achieve is to increment the date by one day. It all works fine except that the setDate method insists on returning me invalid dates sometimes...

For example, if I add 1 day to the 28th February 2011, it will return me 29th February 2011... a date which actually doesn't exist.

Is that a bug/limitation of the JavaScript's native Date/Time API, or am I just doing something wrong? I find it hard to believe that it behaves that way without checking the validity of the date.

 var myDate = new Date(2011, 2, 28);
 alert(myDate);
 myDate.setDate(myDate.getDate() + 1);
 alert(myDate); // 29 February 2011 !

Thanks.

解决方案

You are not in February - month #2 is MARCH

JS months are 0 based

 var myDate = new Date(2011, 1, 28); // 28th of Feb
 alert(myDate);
 myDate.setDate(myDate.getDate() + 1);
 alert(myDate); // 1st of March 2011 !

PS: Where you MAY have some issues are across the daylight savings time if you are creating dates using var d = new Date() and don't normalise on hours by doing d.setHours(0,0,0,0) afterwards

这篇关于JavaScript setDate返回错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆