简体   繁体   English

Javascript将现有日历对象的天数减少了一个月

[英]Javascript add days to a existing calendar object off by one month

I'm trying to read a date from a Calendar object and add a specific amount of days to it (ie 7) 我正在尝试从Calendar对象读取日期,并为其添加特定的天数(即7)

Here is the code that I have: 这是我的代码:

var daysFromBeginDate = parseInt($("#policyDuration").val()) * 7
alert(daysFromBeginDate)
var beginDate = new Date("2015-04-24");
alert(beginDate)
var endDate = new Date("2015-05-08");
alert(beginDate.getDate() + daysFromBeginDate)
endDate.setDate(new Date(beginDate.getDate() + daysFromBeginDate));
alert(endDate.toString())

and I am getting Sun May 31 2015 17:00:000 GMT as my answer. 我得到的Sun May 31 2015 17:00:000 GMTSun May 31 2015 17:00:000 GMT It should be that with one less month, where is the extra month getting added? 应该是少了一个月,多余的月份又在哪里增加呢?

JavaScript using the below call, I found out that the month argument counts starting from zero. 使用以下调用的JavaScript,我发现month参数从零开始计数。

new Date(2015, 3, 1);  // that's the 1st April 2015!

And what is causing the issue is the below code snippet in your code:- 导致此问题的是您的代码中的以下代码片段:-

endDate.getMonth() + 1

That is possibly the reason for your issue.. 那可能是您问题的原因。

EDIT: if the below code 编辑:如果下面的代码

var endDate = new Date("2015-05-08");

is changed to 更改为

var endDate = new Date();

you will get correct output.. 您将获得正确的输出。

it is because setDate sets the day of the month and April has only 30 days so it is rolled over and you get it as May and you get 31 because 24+7 is 31.. 这是因为setDate设置一个月中的某一天,而April仅有30天,因此将其展期,您将其设置为May,因为24 + 7为31,所以您获得31。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM