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


当前回答

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

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

其他回答

我昨晚创建了这些扩展:可以传递正值或负值;

例子:

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;
}

我的简单解决方案是:

nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+1);

这种解决方案在夏时制方面没有问题。此外,还可以添加/减去年、月、日等的任何抵销。

day=new Date(oldDate.getFullYear()-2,oldDate.getMonth()+22,oldDate.getDate()+61);

是正确的代码。

    //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"

已缩小2.39KB。一个文件。https://github.com/rhroyston/clock-js

console.log(clock.wwhat.wayday(clock.now+clock.unit.days))//“星期三”console.log(clock.wwhat.wayday(clock.now+(clock.unit.days*2))//“星期四”console.log(clock.wwhat.wayday(clock.now+(clock.unit.days*3))//“星期五”<script src=“https://raw.githubusercontent.com/rhroyston/clock-js/master/clock.min.js“></script>

有一个setDate和一个getDate方法,允许您执行以下操作:

var newDate = aDate.setDate(aDate.getDate() + numberOfDays);

如果您想减去天数并将日期格式化为可读格式,则应考虑创建一个自定义DateHelper对象,其外观如下:

var日期助手={addDays:函数(aDate,numberOfDays){aDate.setDate(aDate.getDate()+天数);//添加天数return aDate;//返回日期},格式:函数格式(日期){返回[(“0”+date.getDate()).slice(-2),//获取日期并用零填充(“0”+(date.getMonth()+1)).slice(-2),//获取月份并用零填充date.getFullYear()//获取全年].ejoin('/');//把碎片粘在一起}}//有了这个助手,您现在只需使用一行可读代码即可:// ---------------------------------------------------------------------// 1. 获取当前日期// 2. 增加20天// 3. 格式化它// 4. 输出它// ---------------------------------------------------------------------document.body.innerHTML=DateHelper.format(DateHelper.addDays(new Date(),20));

(另见本Fiddle)