获取本周上周本月上月 的开始日期和结束日期
Posted zhaoxiaobei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取本周上周本月上月 的开始日期和结束日期相关的知识,希望对你有一定的参考价值。
方法返回的是一个对象: {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);
},
以上是关于获取本周上周本月上月 的开始日期和结束日期的主要内容,如果未能解决你的问题,请参考以下文章
php一行代码获取本周一,本周日,上周一,上周日,本月一日,本月最后一日,上月一日,上月最后一日日期