方法返回的是一個對象: {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);
},
