获取本周、上周、本月、上月 的开始日期和结束日期
方法返回的是一个对象: {startDate: 年-月-日, endDate: 年-月-日}
使用方法: 获取上月 :getAppointedDate(2, 1) 获取上周 getAppointedDate(1, 1)
获取本月 :getAppointedDate(2, 0) 获取本周 getAppointedDate(1, 0)
获取下月 :getAppointedDate(2, -1) 获取下周 getAppointedDate(1, -1)
这规律大家应该都知道啦吧! html 中: num=0 为本月/本周, 上月/上周 按钮: 《 每点击一次就 num +=1,时间即为getAppointedDate(2, num) ; 下月/下周 按钮:》 num -=1
//获取本周、上周、本月、上月 的开始日期和结束日期 年-月-日
//optType: 1 获取周、 2 获取月
//optPageNum: 0 本周/本月; 上周/月 1 , 1+n
getAppointedDate(optType,optPageNum){
let now = new Date(), //当前日期
nowDayOfWeek = now.getDay(), //今天本周的第几天
nowDay = now.getDate(), //当前日
nowMonth = now.getMonth(), //当前月
nowYear = now.getFullYear(), //当前年
lastMonth = nowMonth -1 ;
let startDate = '', endDate= '';
if(optType==1){
startDate = this.formatDateFn (new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1 - (7*optPageNum)))
endDate = this.formatDateFn (new Date(nowYear, nowMonth, nowDay + 7 - nowDayOfWeek -(7*optPageNum) ))
} else if(optType==2) {
startDate = this.formatDateFn (new Date(nowYear, lastMonth+1-(1*optPageNum), 1))
endDate = this.formatDateFn (new Date(nowYear, lastMonth+1-(1*optPageNum) , this.getMonthDays(nowYear,lastMonth+1-(1*optPageNum)) ))
}
return {startDate: startDate, endDate: endDate}
},
getMonthDays(nowYear,myMonth) {
let monthStartDate = new Date(nowYear, myMonth, 1);
let monthEndDate = new Date(nowYear, myMonth + 1, 1);
let days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
return days;
},
formatDateFn(date) {
let myyear = date.getFullYear();
let mymonth = date.getMonth() + 1;
let myweekday = date.getDate();
if (mymonth < 10) {
mymonth = "0" + mymonth;
}
if (myweekday < 10) {
myweekday = "0" + myweekday;
}
return (myyear + "-" + mymonth + "-" + myweekday);
},