简体   繁体   中英

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)

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. 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.

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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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