如何使用JavaScript将日期添加到当前日期?JavaScript是否有像.NET的AddDay()那样的内置函数?


当前回答

感谢Jason的回答,您的回答符合预期,这里是您的代码和AnthonyWJones的便捷格式的混合:

Date.prototype.addDays = function(days){
    var ms = new Date().getTime() + (86400000 * days);
    var added = new Date(ms);
    return added;
}

其他回答

我们的团队认为date fns是这个领域最好的图书馆。它将日期视为不可变的(Moment.js可能永远不会采用不变性),速度更快,可以模块化加载。

const newDate = DateFns.addDays(oldDate, 2);

我的测试示例可以在日期对象的同一实例中执行减号。

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
    }

那里完成!

    //the_day is 2013-12-31
    var the_day = Date.UTC(2013, 11, 31); 
    // Now, the_day will be "1388448000000" in UTC+8; 
    var the_next_day = new Date(the_day + 24 * 60 * 60 * 1000);
    // Now, the_next_day will be "Wed Jan 01 2014 08:00:00 GMT+0800"

不使用第二个变量,您可以用接下来的x天替换7:

let d=new Date(new Date().getTime() + (7 * 24 * 60 * 60 * 1000));