简体   繁体   English

将天数添加到Javascript日期对象,并增加月数

[英]Add days to Javascript Date object, and also increment month

Looking over the previous questions and answers it 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 ? 有没有一种简单的方法来确保月份正确递增,或者我错过了明显的事情?

You could do it like this: 您可以这样做:

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

The getMonth() call returns a value between 0 and 11, where 0 is January and 11 is December, so 10 means November. getMonth()返回0到11之间的值,其中0是一月,11是十二月,因此10表示十一月。 You need to increment the value by 1 when using it in a string. 在字符串中使用该值时,需要将其值增加1。 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-11 so I made it 11/11/2011 . 它似乎不喜欢2011-11-11所以我做到了11/11/2011 http://jsfiddle.net/9HLSW/ http://jsfiddle.net/9HLSW/

Your code is correct, however you are converting it to a string wrongly . 您的代码正确,但是您将其错误地转换为字符串

getMonth() starts with 0 as January, and ends with 11 as December. getMonth()从1的0开始,到12的11结束。 So all you need to do is add 1 to the month like this: 因此,您需要做的就是将1加到这样的月份:

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

Notice the additional brackets - cos you are performing a math operation while concatenating strings. 注意附加的括号 -您在连接字符串时正在执行数学运算的cos。 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 (ie: January - December). 要查看日期是否正确,请使用endDate.toDateString()以完全限定的名称显示日期(即:1月-12月)。

alert(endDate.toDateString());

For more info on the Date object, check out this section in w3schools 有关Date对象的更多信息,请在w3schools中查看本节

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

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