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

示例

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

特殊情况请自行修改函数

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));
相关推荐
christine-rr几秒前
征文投稿:如何写一份实用的技术文档?——以软件配置为例
运维·前端·网络·数据库·软件构建
_骁2 分钟前
记两次谷歌浏览器升级引起的bug
前端
轻语呢喃12 分钟前
DeepSeek 接口调用:从 HTTP 请求到智能交互
javascript·deepseek
风之舞_yjf43 分钟前
Vue基础(14)_列表过滤、列表排序
前端·javascript·vue.js
belldeep1 小时前
QuickJS 如何发送一封邮件 ?
javascript·curl·smtp·quickjs
BillKu1 小时前
scss(sass)中 & 的使用说明
前端·sass·scss
疯狂的沙粒1 小时前
uni-app 项目支持 vue 3.0 详解及版本升级方案?
前端·vue.js·uni-app
Jiaberrr2 小时前
uniapp Vue2 获取电量的独家方法:绕过官方插件限制
前端·javascript·uni-app·plus·电量
Lhuu(重开版2 小时前
Vue:Ajax
vue.js·ajax·okhttp
谢尔登2 小时前
【React】React 18 并发特性
前端·react.js·前端框架