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


当前回答

您可以尝试:

var days = 50;

const d = new Date();

d.setDate(d.getDate() + days)

这应该很有效。

其他回答

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

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

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

我已经用这种方法在一行中找到了正确的日期,以获得时间加上人们上面所说的一天。

((new Date()).setDate((new Date()).getDate()+1))

我只是想建立一个正常的(新日期()):

(new Date()).getDate()
> 21

使用上面的代码,我现在可以在(newDate())中的Date()中设置所有这些,并且它的行为正常。

(new Date(((new Date()).setDate((new Date()).getDate()+1)))).getDate()
> 22

或获取Date对象:

(new Date(((new Date()).setDate((new Date()).getDate()+1))))

最简单的解决方案。

Date.prototype.addDays=函数(天){this.setDate(this.getDate()+parseInt(天));返回此;};//然后打电话var newDate=新日期().addDays(2)//+2天console.log(newDate);//或var newDate1=新日期().addDays(-2)//-2天console.log(newDate1);

感谢Jason的回答,您的回答符合预期,这里是您的代码和AnthonyWJones的便捷格式的混合:

Date.prototype.addDays = function(days){
    var ms = new Date().getTime() + (86400000 * days);
    var added = new Date(ms);
    return added;
}