为 JavaScript 日期添加天数

如何使用 JavaScript 将天添加到当前Date 。 JavaScript 是否具有诸如. Net 的AddDay类的内置函数?

答案

您可以使用以下方法创建一个:

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

var date = new Date();

alert(date.addDays(5));

如果需要,这可以自动增加月份。例如:

8/31 + 1 天将变为9/1

直接使用setDate的问题在于它是一个 mutator,最好避免这种事情。 ECMA 认为将Date视为可变类而不是不变结构是合适的。

function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}
// Don't do it this way!
function addDaysWRONG(date, days) {
  var result = new Date();
  result.setDate(date.getDate() + days);
  return result;
}
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);
nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+1);
day=new Date(oldDate.getFullYear()-2,oldDate.getMonth()+22,oldDate.getDate()+61);
var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);
var someDate = new Date();
var duration = 2; //In Days
someDate.setTime(someDate.getTime() +  (duration * 24 * 60 * 60 * 1000));
var theDate = new Date(2013, 11, 15);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + 30);
console.log(myNewDate);

如果可以,请使用moment.js 。 JavaScript 没有很好的本机日期 / 时间方法。以下是 Moment 语法的示例:

var nextWeek = moment().add(7, 'days');
alert(nextWeek);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>

参考: http : //momentjs.com/docs/#/manipulating/add/

int days = 1;
var newDate = new Date(Date.now() + days * 24*60*60*1000);
var someDate = new Date();
var expirationDate = someDate.addDays(10);
var previous = someDate.addDays(-5);


Date.prototype.addDays = function (num) {
    var value = this.valueOf();
    value += 86400000 * num;
    return new Date(value);
}

Date.prototype.addSeconds = function (num) {
    var value = this.valueOf();
    value += 1000 * num;
    return new Date(value);
}

Date.prototype.addMinutes = function (num) {
    var value = this.valueOf();
    value += 60000 * num;
    return new Date(value);
}

Date.prototype.addHours = function (num) {
    var value = this.valueOf();
    value += 3600000 * num;
    return new Date(value);
}

Date.prototype.addMonths = function (num) {
    var value = new Date(this.valueOf());

    var mo = this.getMonth();
    var yr = this.getYear();

    mo = (mo + num) % 12;
    if (0 > mo) {
        yr += (this.getMonth() + num - mo - 12) / 12;
        mo += 12;
    }
    else
        yr += ((this.getMonth() + num - mo) / 12);

    value.setMonth(mo);
    value.setYear(yr);
    return value;
}