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


当前回答

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

http://momentjs.com/

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

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

还有很多其他的好东西!

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

其他回答

我想我也会给出答案:就我个人而言,我喜欢尝试避免无谓的变量声明、方法调用和构造函数调用,因为它们的性能都很昂贵。(当然是合理的)我本打算在@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

我实现的最简单的方法是使用Date()本身。`

const days = 15; 
// Date.now() gives the epoch date value (in milliseconds) of current date 
nextDate = new Date( Date.now() + days * 24 * 60 * 60 * 1000)

`

我已经用这种方法在一行中找到了正确的日期,以获得时间加上人们上面所说的一天。

((new Date()).setDate((new Date()).getDate()+1))

我只是想建立一个正常的(新日期()):

(new Date()).getDate()
> 21

使用上面的代码,我现在可以在(newDate())中的Date()中设置所有这些,并且它的行为正常。

(new Date(((new Date()).setDate((new Date()).getDate()+1)))).getDate()
> 22

或获取Date对象:

(new Date(((new Date()).setDate((new Date()).getDate()+1))))
date d = new Date() // current date

date tomorrow = d.setMonth(d.getMonth(),d.getDate()+1) // return a date incremented by 0 months and 1 day

这些答案让我感到困惑,我更喜欢:

var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);

getTime()给出了自1970年以来的毫秒数,86400000是一天中的毫秒数。因此,ms包含所需日期的毫秒。

使用毫秒构造函数可以得到所需的日期对象。