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


当前回答

最简单的解决方案。

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

其他回答

最简单的解决方案。

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

最简单的答案是,假设需要在当前日期上增加1天:

var currentDate = new Date();
var numberOfDayToAdd = 1;
currentDate.setDate(currentDate.getDate() + numberOfDayToAdd );

要逐行向您解释此代码的作用:

创建名为currentDate的当前日期变量。默认情况下,“new Date()”会自动将当前日期分配给变量。创建一个变量以保存要添加到日期的天数(您可以跳过此变量,直接使用第三行中的值)通过给定相同的值+所需的数字来更改Date的值(因为Date是保存在对象中的月份的日期)。切换到下个月将是自动的

    //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"

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

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

我的简单解决方案是:

nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+1);

这种解决方案在夏时制方面没有问题。此外,还可以添加/减去年、月、日等的任何抵销。

day=new Date(oldDate.getFullYear()-2,oldDate.getMonth()+22,oldDate.getDate()+61);

是正确的代码。