在本教程中,我们将学习如何在JavaScript中使用Date 对象将一个当前日期增加7天。
将日期递增7天
要将一个日期增加7天。
-
使用
new Date()构造函数来访问当前日期。 -
我们需要通过使用
setDate()和getDate()方法将日期增加7天。
下面是一个例子。
const current = new Date();
// it adds 1 day to the current date
current.setDate(current.getDate() + 7);
console.log(current.toDateString());
/* If today's date is "Thu Sep 06 2022"
then it returns date after 7 days is "Fri Sep 13 2022" */
即使今天是某月的最后一天,如August 31st 。JavaScript的Date对象也可以算出7天后的日期是September 6th 。
定义
-
setDate()方法将日期(从1到31)作为一个参数,并将该值设置为一个Date对象。 -
getDate()方法得到当前月份的一天(从1-31)。