根据年月日判断某天属于当月第几周

最近有一个需求,需要显示当月第几周,估计甲方是用来统计每周的绩效吧,但是问题来了,只有时间(2021-05-27 14:55:20),寻思着后台给‘第几周’就可以了,哎,后台妹子说不会!!!

该需求定义的当月第一周是从星期一开始,比如说3号是星期一,那么3号就是第一周,1号和2号属于上一月的最后一周

思路:
1、当月的1号是星期几;
2、当月有多少天;
3、1号是星期天的情况;1号是星期一的情况和星期二到星期六的情况

该月的1号 星期几

getMonthFirstDayWeek(year, month) {
  const d = new Date();
  d.setFullYear(year);
  d.setMonth(month);
  d.setDate(1);
  return d.getDay();
},
复制代码

获取一个月的天数

getMonthDayTotal(year, month) {
  const nextMonth = month + 1;
  const d = new Date(year, nextMonth, 0);
  return d.getDate();
},
复制代码

得到当月的第几周

weekNum(employTime) {
  let weekTxt = '';
  const month = parseInt(employTime.slice(5, 7), 10);
  const jsMonth = parseInt(employTime.slice(5, 7), 10) -1;
  const year = parseInt(employTime.slice(0, 4), 10);
  const day = parseInt(employTime.slice(8, 10), 10);
  const startDay = getMonthFirstDayWeek(year, jsMonth); // 该月的1号 星期几
  let monthMondy = '';
  let val = 1;
  if (startDay === 0) { // 1号是星期天
    if (day === 1 && jsMonth === 0) {
      const total2 = getMonthDayTotal(year - 1, jsMonth - 1);
      val =  Math.ceil((total2 - 1) / 7);
    } else if (day === 1 && jsMonth > 0) {
      const startDay3 = getMonthFirstDayWeek(year, jsMonth - 1);
      const total2 = getMonthDayTotal(year, jsMonth - 1);
      val =  Math.ceil((total2 - 1) / 7);
    }
  } else if (startDay === 1) { // 1号是星期一,正好从该天算起
    val = Math.ceil(day / 7);
  } else { //
    monthMondy = 7 - startDay + 2;
    if (day < monthMondy) {
      if (jsMonth === 0) {
        const total2 = getMonthDayTotal(year - 1, jsMonth - 1);
        const startDay2 = getMonthFirstDayWeek(year - 1, jsMonth - 1);
        val =  Math.ceil((total2 - startDay) / 7);
      } else {
      // 获取上一个月的第一周开始的日期
        const total2 = getMonthDayTotal(year, jsMonth - 1);
        const startDay2 = getMonthFirstDayWeek(year, jsMonth - 1);
        val =  Math.ceil((total2 - startDay) / 7);
      }
    } else {
      val = Math.ceil((day - (7 - startDay)) / 7);
    }
  }
  weekTxt = `第${val}周`;
  return weekTxt;
}
复制代码

运行结果:

image.png

1号不是星期一,所以属于5月的周数里的最后一周
image.png

image.png

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享