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


当前回答

不,javascript没有内置函数,但是您可以使用一行简单的代码

timeObject.setDate(timeObject.getDate() + countOfDays);

其他回答

我知道,但有时我喜欢这样:

function addDays(days) {
    return new Date(Date.now() + 864e5 * days);
}

为管道运营商设计的解决方案:

const addDays = days => date => {
  const result = new Date(date);

  result.setDate(result.getDate() + days);

  return result;
};

用法:

// Without the pipeline operator...
addDays(7)(new Date());

// And with the pipeline operator...
new Date() |> addDays(7);

如果您需要更多功能,我建议查看日期fns库。

function addDays(n){
    var t = new Date();
    t.setDate(t.getDate() + n); 
    var month = "0"+(t.getMonth()+1);
    var date = "0"+t.getDate();
    month = month.slice(-2);
    date = date.slice(-2);
     var date = date +"/"+month +"/"+t.getFullYear();
    alert(date);
}

addDays(5);

您可以尝试:

var days = 50;

const d = new Date();

d.setDate(d.getDate() + days)

这应该很有效。

我想我也会给出答案:就我个人而言,我喜欢尝试避免无谓的变量声明、方法调用和构造函数调用,因为它们的性能都很昂贵。(当然是合理的)我本打算在@AnthonyWJones给出的答案下留下评论,但考虑得更好。

// Prototype usage...
Date.prototype.addDays = Date.prototype.addDays || function( days ) {
    return this.setTime( 864E5 * days + this.valueOf() ) && this;
};

// Namespace usage...
namespace.addDaysToDate = function( date, days ) {
    return date.setTime( 864E5 * days + date.valueOf() ) && date;
};

// Basic Function declaration...
function addDaysToDate( date, days ) {
    return date.setTime( 864E5 * days + date.valueOf() ) && date;
};

以上内容将尊重DST。这意味着,如果您添加一个跨越夏令时的天数,则显示的时间(小时)将更改以反映这一点。例子:2014年11月2日02:00是夏令时的结束。

var dt = new Date( 2014, 10, 1, 10, 30, 0 );
console.log( dt );                  // Sat Nov 01 2014 10:30:00
console.log( dt.addDays( 10 ) );    // Tue Nov 11 2014 09:30:00

如果你想保留夏令时的时间(所以10:30仍然是10:30)。。。

// Prototype usage...
Date.prototype.addDays = Date.prototype.addDays || function( days ) {
    return this.setDate( this.getDate() + days ) && this;
};

// Namespace usage...
namespace.addDaysToDate = function( date, days ) {
    return date.setDate( date.getDate() + days ) && date;
};

// Basic Function declaration...
function addDaysToDate( date, days ) {
    return date.setDate( date.getDate() + days ) && date;
};

所以,现在你。。。

var dt = new Date( 2014, 10, 1, 10, 30, 0 );
console.log( dt );                  // Sat Nov 01 2014 10:30:00
console.log( dt.addDays( 10 ) );    // Tue Nov 11 2014 10:30:00