我需要在JavaScript中增加一天的日期值。

例如,我有一个日期值2010-09-11,我需要将第二天的日期存储在一个JavaScript变量中。

如何将日期增加一天?


当前回答

通过原生JS,添加一天你可以做以下事情:

let date = new Date(); // today
date.setDate(date.getDate() + 1) // tomorrow

另一种选择是使用矩库:

const date = moment().add(14, "days").toDate()

其他回答

var myDate = new Date();

//add a day to the date
myDate.setDate(myDate.getDate() + 1);

使用这个函数,它解决了我的问题:

    let nextDate = (daysAhead:number) => {
      const today = new Date().toLocaleDateString().split('/')
      const invalidDate = new Date(`${today[2]}/${today[1]}/${Number(today[0])+daysAhead}`)
      if(Number(today[1]) === Number(12)){
        return new Date(`${Number(today[2])+1}/${1}/${1}`)
      }
      if(String(invalidDate) === 'Invalid Date'){
        return new Date(`${today[2]}/${Number(today[1])+1}/${1}`)
      }
        return new Date(`${today[2]}/${Number(today[1])}/${Number(today[0])+daysAhead}`)
    }

这个答案中的任何一个例子似乎都不适用于日光节约时间调整日。在这些日子里,一天的小时数不是24小时(是23小时还是25小时,取决于你是“向前跳”还是“向后跳”)。

下面的AddDays javascript函数说明了夏令时:

function addDays(date, amount) {
  var tzOff = date.getTimezoneOffset() * 60 * 1000,
      t = date.getTime(),
      d = new Date(),
      tzOff2;

  t += (1000 * 60 * 60 * 24) * amount;
  d.setTime(t);

  tzOff2 = d.getTimezoneOffset() * 60 * 1000;
  if (tzOff != tzOff2) {
    var diff = tzOff2 - tzOff;
    t += diff;
    d.setTime(t);
  }

  return d;
}

以下是我用来测试该功能的测试:

    var d = new Date(2010,10,7);
    var d2 = AddDays(d, 1);
    document.write(d.toString() + "<br />" + d2.toString());

    d = new Date(2010,10,8);
    d2 = AddDays(d, -1)
    document.write("<hr /><br />" +  d.toString() + "<br />" + d2.toString());

    d = new Date('Sun Mar 27 2011 01:59:00 GMT+0100 (CET)');
    d2 = AddDays(d, 1)
    document.write("<hr /><br />" +  d.toString() + "<br />" + d2.toString());

    d = new Date('Sun Mar 28 2011 01:59:00 GMT+0100 (CET)');
    d2 = AddDays(d, -1)
    document.write("<hr /><br />" +  d.toString() + "<br />" + d2.toString());

通过原生JS,添加一天你可以做以下事情:

let date = new Date(); // today
date.setDate(date.getDate() + 1) // tomorrow

另一种选择是使用矩库:

const date = moment().add(14, "days").toDate()

最简单的方法是转换为毫秒,然后加上1000*60*60*24毫秒,例如:

var tomorrow = new Date(today.getTime()+1000*60*60*24);