如何使用JavaScript将日期添加到当前日期?JavaScript是否有像.NET的AddDay()那样的内置函数?
当前回答
new Date(Date.now() + 2000 * 86400)
此代码段使用“2000”参数为当前日期添加两天。您可以通过更新第二个参数中的“2000”值来调整天数。
您可以使用这种单行格式,使用本机JavaScript日期将日期添加到当前日期。
其他回答
我总结了小时和天。。。
Date.prototype.addDays = function(days){
days = parseInt(days, 10)
this.setDate(this.getUTCDate() + days);
return this;
}
Date.prototype.addHours = function(hrs){
var hr = this.getUTCHours() + parseInt(hrs , 10);
while(hr > 24){
hr = hr - 24;
this.addDays(1);
}
this.setHours(hr);
return this;
}
试试这个
function addDays(date,days) {
var one_day=1000*60*60*24;
return new Date(date.getTime()+(days*one_day)).toLocaleDateString();
}
我的简单解决方案是:
nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+1);
这种解决方案在夏时制方面没有问题。此外,还可以添加/减去年、月、日等的任何抵销。
day=new Date(oldDate.getFullYear()-2,oldDate.getMonth()+22,oldDate.getDate()+61);
是正确的代码。
编辑:您可以这样做,而不是setTime()(或setHours()):
Date.prototype.addDays= function(d){
this.setDate(this.getDate() + d);
return this;
};
var tomorrow = new Date().addDays(1);
Old:
可以使用setHours()代替setTime():
Date.prototype.addDays= function(d){
this.setHours(this.getHours() + d * 24);
return this;
};
var tomorrow = new Date().addDays(1);
查看JSFiddle。。。
Try
var someDate = new Date();
var duration = 2; //In Days
someDate.setTime(someDate.getTime() + (duration * 24 * 60 * 60 * 1000));
使用setDate()添加日期并不能解决您的问题,请尝试在2月份添加一些天,如果您尝试在其中添加新的天,则不会产生您预期的结果。
推荐文章
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- SQL Developer只返回日期,而不是时间。我怎么解决这个问题?
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?