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


当前回答

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

我的简单解决方案是:

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

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

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

是正确的代码。

只是花了很长时间试图弄清楚今年的交易是什么,而不是在下面的主要例子中添加。

如果你只想在你拥有的日期上加上n天,最好就这样做:

myDate.setDate(myDate.getDate()+n);

或冗长的版本

var theDate = new Date(2013, 11, 15);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + 30);
console.log(myNewDate);

今天/明天的事情令人困惑。通过将当前日期设置为新的日期变量,您将搞乱年份值。如果你从最初的日期开始工作,你就不会。

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

通过改用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;
}

不使用第二个变量,您可以用接下来的x天替换7:

let d=new Date(new Date().getTime() + (7 * 24 * 60 * 60 * 1000));