获取本周、上周、本月、上月,下月 的开始日期和结束日期

方法返回的是一个对象:  {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);

},

转载的链接
https://www.cnblogs.com/zhaoxiaobei/p/10142990.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值