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


当前回答

new Date(Date.now() + 2000 * 86400)

此代码段使用“2000”参数为当前日期添加两天。您可以通过更新第二个参数中的“2000”值来调整天数。

您可以使用这种单行格式,使用本机JavaScript日期将日期添加到当前日期。

其他回答

您可以在此处创建自定义助手函数

function plusToDate(currentDate, unit, howMuch) {

    var config = {
        second: 1000, // 1000 miliseconds
        minute: 60000,
        hour: 3600000,
        day: 86400000,
        week: 604800000,
        month: 2592000000, // Assuming 30 days in a month
        year: 31536000000 // Assuming 365 days in year
    };

    var now = new Date(currentDate);

    return new Date(now + config[unit] * howMuch);
}

var today = new Date();
var theDayAfterTommorow = plusToDate(today, 'day', 2);

顺便说一句,这是一个通用的解决方案,可以根据需要添加秒、分钟或天。

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

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

我对所提出的解决方案的夏令时有问题。

通过改用getUTCDate/setUTCDate,我解决了问题。

// Curried, so that I can create helper functions like `add1Day`
const addDays = num => date => {
  // Make a working copy so we don't mutate the supplied date.
  const d = new Date(date);

  d.setUTCDate(d.getUTCDate() + num);

  return d;
}
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);

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

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