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


当前回答

Try

var someDate = new Date();
var duration = 2; //In Days
someDate.setTime(someDate.getTime() +  (duration * 24 * 60 * 60 * 1000));

使用setDate()添加日期并不能解决您的问题,请尝试在2月份添加一些天,如果您尝试在其中添加新的天,则不会产生您预期的结果。

其他回答

我的测试示例可以在日期对象的同一实例中执行减号。

Date.prototype.reset=函数(){let newDate=新日期(this.timeStamp)this.setFullYear(newDate.getFullYear)this.setMonth(newDate.getMonth())this.setDate(newDate.getDate())this.setHours(newDate.getHours())this.set分钟(newDate.getMinutes())this.setSeconds(newDate.getSeconds())this.set毫秒(newDate.getMilliseconds())}Date.prototype.addDays=函数(天){this.timeStamp=此[Symbol.toPrimitive]('编号')let daysInMiliseconds=(天*(1000*60*60*24))this.timeStamp=this.timeStamp+天毫秒this.reset()}Date.prototype.minusDays=函数(天){this.timeStamp=此[Symbol.toPrimitive]('编号')let daysInMiliseconds=(天*(1000*60*60*24))如果(daysInMiliseconds<=this.timeStamp){this.timeStamp=this.timeStamp-天毫秒this.reset()}}var temp=新日期(Date.now())//从现在开始console.log(temp.toDateString())临时添加天数(31)console.log(temp.toDateString())温度-天(5)console.log(temp.toDateString())

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

((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))))
function addDays(n){
    var t = new Date();
    t.setDate(t.getDate() + n); 
    var month = "0"+(t.getMonth()+1);
    var date = "0"+t.getDate();
    month = month.slice(-2);
    date = date.slice(-2);
     var date = date +"/"+month +"/"+t.getFullYear();
    alert(date);
}

addDays(5);

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

您可以使用JavaScript,不需要jQuery:

var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd); 
Formatting to dd/mm/yyyy :

var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();

var someFormattedDate = dd + '/'+ mm + '/'+ y;