如何使用JavaScript将日期添加到当前日期?JavaScript是否有像.NET的AddDay()那样的内置函数?
当前回答
我知道,但有时我喜欢这样:
function addDays(days) {
return new Date(Date.now() + 864e5 * days);
}
其他回答
最简单的解决方案。
Date.prototype.addDays=函数(天){this.setDate(this.getDate()+parseInt(天));返回此;};//然后打电话var newDate=新日期().addDays(2)//+2天console.log(newDate);//或var newDate1=新日期().addDays(-2)//-2天console.log(newDate1);
setDate()的mozilla文档并不表示它将处理月末场景。看见https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
设置日期()
根据当地时间设置指定日期的月份日期(1-31)。
这就是我在需要添加天数时使用setTime()的原因。
为管道运营商设计的解决方案:
const addDays = days => date => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
用法:
// Without the pipeline operator...
addDays(7)(new Date());
// And with the pipeline operator...
new Date() |> addDays(7);
如果您需要更多功能,我建议查看日期fns库。
我的测试示例可以在日期对象的同一实例中执行减号。
Date.prototype.reset=函数(){let newDate=新日期(this.timeStamp)this.setFullYear(newDate.getFullYear)this.setMonth(newDate.getMonth())this.setDate(newDate.getDate())this.setHours(newDate.getHours())this.set分钟(newDate.getMinutes())this.setSeconds(newDate.getSeconds())this.set毫秒(newDate.getMilliseconds())}Date.prototype.addDays=函数(天){this.timeStamp=此[Symbol.toPrimitive]('编号')let daysInMiliseconds=(天*(1000*60*60*24))this.timeStamp=this.timeStamp+天毫秒this.reset()}Date.prototype.minusDays=函数(天){this.timeStamp=此[Symbol.toPrimitive]('编号')let daysInMiliseconds=(天*(1000*60*60*24))如果(daysInMiliseconds<=this.timeStamp){this.timeStamp=this.timeStamp-天毫秒this.reset()}}var temp=新日期(Date.now())//从现在开始console.log(temp.toDateString())临时添加天数(31)console.log(temp.toDateString())温度-天(5)console.log(temp.toDateString())
我真不敢相信,5年后,这条线索中没有捷径可走!SO:要获得一天中相同的时间,而不考虑夏季的干扰:
Date.prototype.addDays = function(days)
{
var dat = new Date( this.valueOf() )
var hour1 = dat.getHours()
dat.setTime( dat.getTime() + days * 86400000) // 24*60*60*1000 = 24 hours
var hour2 = dat.getHours()
if (hour1 != hour2) // summertime occured +/- a WHOLE number of hours thank god!
dat.setTime( dat.getTime() + (hour1 - hour2) * 3600000) // 60*60*1000 = 1 hour
return dat
or
this.setTime( dat.getTime() ) // to modify the object directly
}
那里完成!