首先定义两个方法,相当于进行了封装
/** * * @param dateNow :Date类 * @param intervalDays :间隔天数 * @param bolPastTime :Boolean,判断在参数date之前,还是之后, */ function 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; } function 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 + '' }
具体获取数据如下:(调用上面方法即可)
//获取当前日期(2020-03-24) var date = new Date(); var list = this.getDateRange(date,6,true) console.log("获取近一周日期范围: 开始日期:"+list[0]+"; 结束日期:"+list[1]); var list = this.getDateRange(date,30,true) console.log("获取近一个月日期范围: 开始日期:"+list[0]+"; 结束日期:"+list[1]); var list = this.getDateRange(date,0,true) console.log("获取今天日期范围: 开始日期:"+list[0]+"; 结束日期:"+list[1]); var list = this.getDateRange(date,1,true) console.log("获取昨天日期范围: 开始日期:"+list[0]+"; 结束日期:"+list[0]); var list = this.getDateRange(date,6,false) console.log("获取下一周日期范围: 开始日期:"+list[0]+"; 结束日期:"+list[1]); var list = this.getDateRange(date,30,false) console.log("获取下一个月日期范围: 开始日期:"+list[0]+"; 结束日期:"+list[1]);
具体打印结果还请亲自动手测试;
参考原文:https://blog.csdn.net/qq_41090476/article/details/96133830