向 Javascript 日期对象添加天数,并增加月份

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8081500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:11:33  来源:igfitidea点击:

Add days to Javascript Date object, and also increment month

javascriptdate

提问by NimChimpsky

Looking over the previous questions and answersit appeared this should work :

查看以前的问题和答案,似乎这应该有效:

var palindrome = new Date('2011-11-11');
var december = new Date('2011-11-11');

december.setDate(palindrome.getDate()+20); 
//should be december, but in fact loops back over to Nov 1st)

my jsFiddle

我的jsFiddle

is there a simple way to ensure that months are incremented correctly, or have I missed something obvious ?

是否有一种简单的方法可以确保月份正确递增,或者我是否遗漏了一些明显的内容?

回答by nogola

You could do it like this:

你可以这样做:

var dayOffset = 20;
var millisecondOffset = dayOffset * 24 * 60 * 60 * 1000;
december.setTime(december.getTime() + millisecondOffset); 

回答by tvanfosson

The getMonth()call returns a value between 0 and 11, where 0 is January and 11 is December, so 10 means November. You need to increment the value by 1 when using it in a string. If you simply output it as a string you'll see that it has the correct date. Note I also had to change the starting date format. It didn't seem to like 2011-11-11so I made it 11/11/2011. http://jsfiddle.net/9HLSW/

getMonth()调用返回0到11,其中0是一月和11月之间的值,所以10种月手段。在字符串中使用时,需要将该值加 1。如果您只是将其作为字符串输出,您将看到它具有正确的日期。注意我还必须更改开始日期格式。它似乎不喜欢2011-11-11所以我做到了11/11/2011http://jsfiddle.net/9HLSW/

回答by Samuel Liew

Your code is correct, however you are converting it to a string wrongly.

您的代码是正确的,但是您错误地将其转换为字符串

getMonth()starts with 0as January, and ends with 11as December. So all you need to do is add 1 to the month like this:

getMonth()0开始作为一月,以11结束作为十二月。所以你需要做的就是像这样给月份加 1:

alert(endDate.getFullYear() + "-" + (endDate.getMonth()+1) +"-"+ endDate.getDate());   

Notice the additional brackets- cos you are performing a math operation while concatenating strings. You won't want to end up with "101" as the month.

请注意附加括号- 因为您在连接字符串时正在执行数学运算。您不会希望以“ 101”作为月份结束。

To see whether you got the date correct, use endDate.toDateString()to display the date in a fully qualified name (i.e.: January - December).

要查看日期是否正确,请使用endDate.toDateString()以完全限定名称显示日期(即:一月 - 十二月)。

alert(endDate.toDateString());

For more info on the Date object, check out this sectionin w3schools

有关 Date 对象的更多信息,请查看w3schools 中的此部分