如何使用JavaScript添加迄今为止的几周? [英] How to add weeks to date using javascript?
问题描述
JavaScript绝对不是我的强项。我已经尝试了几个小时,但似乎一直无法将日期格式化。
Javascript definitely isn't my strongest point. I've been attempting this for a couple of hours now and seem to be getting stuck with date formatting somewhere.
我有一个用户选择日期(dd / mm / yyyy),然后将采用该日期并将其添加2周,然后将日期复制到另一个表单字段。
I have a form where a user selected a date (dd/mm/yyyy) and then this date will be taken and 2 weeks will be added to it and then date will be copied to another form field.
我在下面的最新尝试甚至都没有添加日期,只是将一个表单字段中的选定日期复制到了另一个日期,如果我选择了 03/02/2012,它将输出 Fri Mar 02 2012 00:00:00 GMT + 0000(格林尼治标准时间)',因此其以美国格式以及完整日期输出。如何以相同的格式将其发布并添加2周?
My latest attempt below isn't even adding a date yet just copying the selected date in one form field to another, if I select '03/02/2012', it outputs 'Fri Mar 02 2012 00:00:00 GMT+0000 (GMT Standard Time)', so its outputting in American format as well as the full date. How to I get it to out put in the same format and add 2 weeks?
function LicenceToOccupy(acceptCompletionDate)
{
var date1 = new Date(acceptCompletionDate);
document.frmAccept.acceptLicence.value = date1;
}
推荐答案
您可以这样做:
let numWeeks = 2;
let now = new Date();
now.setDate(now.getDate() + numWeeks * 7);
alert(now);
您可以看到小提琴此处。
根据 MDN中的文档
setDate()方法设置Date对象相对于日期的日期当前设置月份的开始。
The setDate() method sets the day of the Date object relative to the beginning of the currently set month.
这篇关于如何使用JavaScript添加迄今为止的几周?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!