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


当前回答

我试图解决类似的问题,我更喜欢getTime方法,但有一些奇怪的基于时区的副作用。

ofc将“今天”替换为您需要的任何日期,并将时间也输入。关键是获取UTC时间,然后用毫秒来做加法,以避免这些副作用。

var now = new Date(Date.now());
var today = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));

const dayInMs = 86400000; //24 hours
const tomorrow = new Date(today.getTime() + dayInMs);    

其他回答

最简单的解决方案。

Date.prototype.addDays=函数(天){this.setDate(this.getDate()+parseInt(天));返回此;};//然后打电话var newDate=新日期().addDays(2)//+2天console.log(newDate);//或var newDate1=新日期().addDays(-2)//-2天console.log(newDate1);

派对迟到了,但如果你使用jQuery,那么有一个名为Moment的优秀插件:

http://momentjs.com/

var myDateOfNowPlusThreeDays = moment().add(3, "days").toDate();

http://momentjs.com/docs/#/manipulating/

还有很多其他的好东西!

编辑:由于aikeru的评论,jQuery引用被删除

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

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

减去30天使用(24小时=86400000ms)

new Date(+yourDate - 30 *86400000)

var yourDate=新日期();var d=新日期(+yourDate-30*86400000)控制台日志(d)

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

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())