根据年月计算当月有哪几个周,及每周的起止日期

示例

传参数年、月,返回包含当月的所有周数、及周的起止日期,支持跨月

特殊情况请自行修改函数

javascript 复制代码
console.log(getWeeksInMonth(2024, 9));

返回如下

源码

源码以elementUI的周选择框的起止日期作为参考

javascript 复制代码
function getWeeksInMonth(year, month) {
  // 计算指定年月的第一个月的第一天是星期几
  const firstDayOfMonth = new Date(year, month - 1, 1);
  const firstDayOfWeek = firstDayOfMonth.getDay(); // 星期天为0, 星期一为1, ..., 星期六为6

  // 计算指定年月的最后一天是星期几
  const lastDayOfMonth = new Date(year, month, 0);

  // 计算第一周的开始日期(可能是上个月的日期)
  const firstWeekStartDate = new Date(firstDayOfMonth);
  firstWeekStartDate.setDate(firstDayOfMonth.getDate() - (firstDayOfWeek + 6) % 7);

  // 初始化周数和日期数组
  let weeks = [];
  let currentDate = new Date(firstWeekStartDate);

  // 循环计算每周的起止日期
  while (currentDate <= lastDayOfMonth) {
    // 计算本周的结束日期(如果是月底,则可能跨月)
    const endOfWeek = new Date(currentDate);
    endOfWeek.setDate(currentDate.getDate() + 6);

    // 添加周信息到数组
    weeks.push({
      week: getISOWeek(currentDate),
      beginDate: formatDate(currentDate),
      endDate: formatDate(endOfWeek)
    });

    // 更新currentDate为下一周的开始日期
    currentDate = new Date(endOfWeek);
    currentDate.setDate(endOfWeek.getDate() + 1);
  }
  return weeks;
}

// 格式化日期为YYYY-MM-DD格式
function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 获取ISO周数
function getISOWeek(date) {
  const target = new Date(date.valueOf());
  const dayNr = (date.getDay() + 6) % 7;
  target.setDate(target.getDate() - dayNr + 3);
  const firstThursday = target.valueOf();
  target.setMonth(0, 1);
  if (target.getDay() !== 4) {
    target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
  }
  const week1 = new Date(target.getFullYear(), 0, 4);
  return 1 + Math.ceil((firstThursday - week1) / 604800000);
}

// 示例:获取2024年9月的周数及起止日期
console.log(getWeeksInMonth(2024, 9));
相关推荐
世俗ˊ19 分钟前
CSS入门笔记
前端·css·笔记
子非鱼92119 分钟前
【前端】ES6:Set与Map
前端·javascript·es6
6230_24 分钟前
git使用“保姆级”教程1——简介及配置项设置
前端·git·学习·html·web3·学习方法·改行学it
想退休的搬砖人33 分钟前
vue选项式写法项目案例(购物车)
前端·javascript·vue.js
加勒比海涛1 小时前
HTML 揭秘:HTML 编码快速入门
前端·html
啥子花道1 小时前
Vue3.4 中 v-model 双向数据绑定新玩法详解
前端·javascript·vue.js
麒麟而非淇淋1 小时前
AJAX 入门 day3
前端·javascript·ajax
茶茶只知道学习1 小时前
通过鼠标移动来调整两个盒子的宽度(响应式)
前端·javascript·css
清汤饺子1 小时前
实践指南之网页转PDF
前端·javascript·react.js
蒟蒻的贤1 小时前
Web APIs 第二天
开发语言·前端·javascript