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


当前回答

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

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

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

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

其他回答

以下是在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);

在java脚本中添加日期的非常简单的代码。

var d=新日期();d.setDate(d.getDate()+提示('你想在这里添加多少天'));警报(d);

您可以使用以下选项创建一个:-

Date.prototype.addDays=函数(天){var date=新日期(this.valueOf());date.setDate(date.getDate()+天);返回日期;}var date=新日期();console.log(date.addDays(5));

这会在必要时自动增加月份。例如:

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

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

我总结了小时和天。。。

Date.prototype.addDays = function(days){
    days = parseInt(days, 10)
    this.setDate(this.getUTCDate() + days);
    return this;
}

Date.prototype.addHours = function(hrs){
    var hr = this.getUTCHours() + parseInt(hrs  , 10);
    while(hr > 24){
      hr = hr - 24;
      this.addDays(1);
    }

    this.setHours(hr);
    return this;
}
    //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"