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
Add 5 days to the current date using JavaScript
提问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 Date
variable (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 click
handler function. Something like:
将以上所有内容放在您的click
处理程序函数中。就像是:
document.getElementById('dateBtn').onclick = function () {
var dt = new Date();
dt.setDate(dt.getDate() + 5);
alert(dt);
};
回答by user1549458
回答by Bryce
create a Date
instance 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
。