let d = new Date('2018,7,26');
let c = new Date()
c.setDate(d.getDate() + 1)
document.write(c);
document.write("<br>");
c.setDate(d.getDate() + 5)
document.write(c);
document.write("<br>");
c.setDate(d.getDate() + 6)
document.write(c);
document.write("<br>");
c.setDate(d.getDate() + 7)
document.write(c);
document.write("<br>");
c.setDate(d.getDate() + 8)
document.write(c);
document.write("<br>");
c.setDate(d.getDate() + 9)
document.write(c);
document.write("<br>");
c.setDate(d.getDate() + 10)
document.write(c);
document.write("<br>");
运行这段代码的输出:
Fri Jul 27 2018 14:35:17 GMT+0530 (India Standard Time)
Tue Jul 31 2018 14:35:17 GMT+0530 (India Standard Time)
Wed Aug 01 2018 14:35:17 GMT+0530 (India Standard Time)
Sun Sep 02 2018 14:35:17 GMT+0530 (India Standard Time)
Thu Oct 04 2018 14:35:17 GMT+0530 (India Standard Time)
Sun Nov 04 2018 14:35:17 GMT+0530 (India Standard Time)
Thu Dec 06 2018 14:35:17 GMT+0530 (India Standard Time)
这看起来像一个错误。如果今天是 2018-07-26(即 7 月 26 日),则加上 7 天应该是 2018-08-02(即 8 月 2 日)。但是,现在是 9 月 2 日。然后,进一步添加会使情况变得更糟。
解决这个问题的方法是什么?如何在 JS
中正确增加日期?
最佳答案
当您将 c
设置为超过一个月中的天数时,它会增加 c
中的月份。您的代码的问题是您没有清除 c
的值,并且它在 c
中随着每个具有参数的 setDate
不断增加当前月份 > 31
。
关于javascript - 这真的是 JAVASCRIPT 中的错误还是我对日期、数据类型做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51535087/