有没有一种简单的方法来获取olain JavaScript日期(例如今天)并返回X天?
例如,如果我想计算今天前5天的日期。
有没有一种简单的方法来获取olain JavaScript日期(例如今天)并返回X天?
例如,如果我想计算今天前5天的日期。
当前回答
如果你想把这一切都放在一行。
从今天起5天
//past
var fiveDaysAgo = new Date(new Date().setDate(new Date().getDate() - 5));
//future
var fiveDaysInTheFuture = new Date(new Date().setDate(new Date().getDate() + 5));
特定日期后5天
var pastDate = new Date('2019-12-12T00:00:00');
//past
var fiveDaysAgo = new Date(new Date().setDate(pastDate.getDate() - 5));
//future
var fiveDaysInTheFuture = new Date(new Date().setDate(pastDate.getDate() + 5));
我写了一个你可以使用的函数。
函数AddOrSubactDays(startingDate,number,add){if(添加){返回新日期(newDate().setDate(startingDate.getDate()+number));}其他{返回新日期(newDate().setDate(startingDate.getDate()-number));}}console.log('Today:'+new Date());console.log('Future:'+AddOrSubactDays(new Date(),5,true));console.log('Last:'+AddOrSubactDays(new Date(),5,false));
其他回答
请参见以下代码,从当前日期减去天数。此外,根据减去的日期设置月份。
var today = new Date();
var substract_no_of_days = 25;
today.setTime(today.getTime() - substract_no_of_days* 24 * 60 * 60 * 1000);
var substracted_date = (today.getMonth()+1) + "/" +today.getDate() + "/" + today.getFullYear();
alert(substracted_date);
一些现有的解决方案很接近,但并不完全符合我的要求。此函数可处理正值或负值,并处理边界情况。
function addDays(date, days) {
return new Date(
date.getFullYear(),
date.getMonth(),
date.getDate() + days,
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
);
}
我注意到getDays+X在日/月范围内不起作用。只要您的日期不早于1970年,就可以使用getTime。
var todayDate = new Date(), weekDate = new Date();
weekDate.setTime(todayDate.getTime()-(7*24*3600000));
var d=新日期();document.write('今天是:'+d.toLocaleString());d.setDate(d.getDate()-31);document.write('<br>5天前是:'+d.toLocaleString());
我为Date制作了这个原型,这样我就可以传递负值来减去天数,传递正值来添加天数。
if(!Date.prototype.adjustDate){
Date.prototype.adjustDate = function(days){
var date;
days = days || 0;
if(days === 0){
date = new Date( this.getTime() );
} else if(days > 0) {
date = new Date( this.getTime() );
date.setDate(date.getDate() + days);
} else {
date = new Date(
this.getFullYear(),
this.getMonth(),
this.getDate() - Math.abs(days),
this.getHours(),
this.getMinutes(),
this.getSeconds(),
this.getMilliseconds()
);
}
this.setTime(date.getTime());
return this;
};
}
因此,为了使用它,我可以简单地写下:
var date_subtract = new Date().adjustDate(-4),
date_add = new Date().adjustDate(4);