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


当前回答

已缩小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>

其他回答

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

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

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

编辑:您可以这样做,而不是setTime()(或setHours()):

Date.prototype.addDays= function(d){
  this.setDate(this.getDate() + d);
  return this;
};

var tomorrow = new Date().addDays(1);

Old:

可以使用setHours()代替setTime():

Date.prototype.addDays= function(d){
    this.setHours(this.getHours() + d * 24);
    return this;
};

var tomorrow = new Date().addDays(1);

查看JSFiddle。。。

为什么这么复杂?

假设您将要添加的天数存储在一个名为days_to_add的变量中。

那么这个简短的应该做到:

calc_date = new Date(Date.now() +(days_to_add * 86400000));

使用Date.now(),您可以获得实际的unix时间戳(以毫秒为单位),然后添加您想要添加的天数。一天为24h60min60s*1000ms=86400000 ms或864E5。

int days = 1;
var newDate = new Date(Date.now() + days * 24*60*60*1000);

代码笔

var天数=2;var newDate=新日期(Date.now()+天*24*60*60*1000);document.write(“今日:<em>”);document.write(new Date());document.write('</em><br/>新建:<strong>');document.write(newDate);

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

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