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


当前回答

我使用的是:

new Date(dateObject.getTime() + amountOfDays * 24 * 60 * 60 * 1000)

节省时间的工作:

new Date(new Date(2014, 2, 29, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)

与新年一起工作:

new Date(new Date(2014, 11, 31, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)

它可以参数化:

function DateAdd(source, amount, step) {
  var factor = 1;
  if (step == "day") factor = 24 * 60 * 60 * 1000;
  else if (step == "hour") factor = 60 * 60 * 1000;
  ...
  new Date(source.getTime() + amount * factor);
}

其他回答

以下是在Javascript中为特定日期添加日期、月份和年份的方法。

// To add Days
var d = new Date();
d.setDate(d.getDate() + 5);

// To add Months
var m = new Date();
m.setMonth(m.getMonth() + 5);

// To add Years
var y = new Date();
y.setFullYear(y.getFullYear() + 5);

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

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

只是花了很长时间试图弄清楚今年的交易是什么,而不是在下面的主要例子中添加。

如果你只想在你拥有的日期上加上n天,最好就这样做:

myDate.setDate(myDate.getDate()+n);

或冗长的版本

var theDate = new Date(2013, 11, 15);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + 30);
console.log(myNewDate);

今天/明天的事情令人困惑。通过将当前日期设置为新的日期变量,您将搞乱年份值。如果你从最初的日期开始工作,你就不会。

这类函数有问题,我用parseInt()解决

Date.prototype.addDays = function(dias) {

    var date = new Date(this.valueOf());
    date.setDate(parseInt(date.getDate()) + parseInt(dias));
    return date;
}

Date.prototype.addMonths = function(months) {
    var date = new Date(this.valueOf());
    date.setMonth(parseInt(date.getMonth()) + parseInt(months));
    return date;
}


Date.prototype.addYears = function(years) {
    var date = new Date(this.valueOf());
    date.setFullYear(parseInt(date.getFullYear()) + parseInt(years));
    return date;
}
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);

小心,因为这可能很棘手。当设置明天时,它仅在当前值与今天的年份和月份匹配时有效。然而,通常将日期设置为“32”这样的数字仍然可以很好地将其移动到下一个月。