Html 使用 JavaScript 将 5 天添加到当前日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15910761/
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-08-29 07:23:35  来源:igfitidea点击:

Add 5 days to the current date using JavaScript

javascripthtmldatetimebutton

提问by user2262982

I am trying to add 5 days to today's date using JavaScript. I am also trying to add this function into a button so that the result comes in an alert box when I click it, not as soon as I open the page.

我正在尝试使用 JavaScript 将今天的日期添加 5 天。我还尝试将此功能添加到按钮中,以便当我单击它时结果出现在警告框中,而不是在我打开页面后立即出现。

I am new to JavaScript and trying very hard to learn.

我是 JavaScript 的新手,并且非常努力地学习。

Any help? Thanks!

有什么帮助吗?谢谢!

回答by Artyom Neustroev

Declare a Datevariable (it will be set to current date/time):

声明一个Date变量(它将被设置为当前日期/时间):

var dt = new Date();

Add 5 days:

加5天:

dt.setDate(dt.getDate() + 5);

Put all the above in your clickhandler function. Something like:

将以上所有内容放在您的click处理程序函数中。就像是:

document.getElementById('dateBtn').onclick = function () {
   var dt = new Date();
   dt.setDate(dt.getDate() + 5);
   alert(dt);
};

FIDDLE EXAMPLE

小提琴示例

回答by user1549458

var date = new Date();          // Get current Date

date.setDate(date.getDate()+5); // add 5 days to the current date

For more information see Date.

有关更多信息,请参阅Date

回答by Bryce

Might be overkill but moment.jscould be useful to you.

可能有点矫枉过正,但moment.js可能对你有用。

回答by Bryce

create a Dateinstance five days:

创建一个Date实例五天:

var fiveDaysLater = new Date( AnyYourDate.getTime() );
fiveDaysLater.setDate(fiveDaysLater.getDate() + 5);

回答by HardScale

JavaScript stores dates and times in milliseconds. So, add 5 days worth:

JavaScript 以毫秒为单位存储日期和时间。因此,增加 5 天的价值:

var fiveDaysLater = new Date(0,0,0,0,0,0,Date.now() + 5 * 24 * 60 * 60 * 1000);

Date.now() returns a value in milliseconds. The date constructor (new Date) then makes a new Date object (hence the keyword new) using this value, plus the five days of milliseconds, and initializes the variable fiveDaysLater.

Date.now() 以毫秒为单位返回一个值。然后日期构造函数 ( new Date)new使用这个值加上五天的毫秒数来创建一个新的 Date 对象(因此是关键字),并初始化变量fiveDaysLater