在Vue的methods中写入下面两个方法,其中dateNow是当前时间,intervalDay是间隔天数,bolPastTime是判断日期间隔向前或向后的flag,true为过去,false为以后。
getDateRange(dateNow,intervalDays,bolPastTime){
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if(bolPastTime == true){
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(this.formateDate(lastDay));
list.push(this.formateDate(dateNow));
}else{
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(this.formateDate(dateNow));
list.push(this.formateDate(lastDay));
}
return list;
},
formateDate(time){
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
},
测试:
var date = new Date();
var list = this.getDateRange(date, 30, true);
console.log("最近一个月", list);
结果:
总结:不仅可以看最近一个月,最近一周,最近20天或者未来一周,未来一个月都可以。只要替换中间的间隔时间就好了。
感谢原博:https://blog.csdn.net/qq_41090476/article/details/96133830