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

示例

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

特殊情况请自行修改函数

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));
相关推荐
Nicholas682 分钟前
flutterAppBar之SystemUiOverlayStyle源码解析(一)
前端
黑客飓风19 分钟前
JavaScript 性能优化实战大纲
前端·javascript·性能优化
emojiwoo2 小时前
【前端基础知识系列六】React 项目基本框架及常见文件夹作用总结(图文版)
前端·react.js·前端框架
张人玉2 小时前
XML 序列化与操作详解笔记
xml·前端·笔记
杨荧2 小时前
基于Python的宠物服务管理系统 Python+Django+Vue.js
大数据·前端·vue.js·爬虫·python·信息可视化
YeeWang3 小时前
🎉 Eficy 让你的 Cherry Studio 直接生成可预览的 React 页面
前端·javascript
gnip3 小时前
Jenkins部署前端项目实战方案
前端·javascript·架构
Orange3015113 小时前
《深入源码理解webpack构建流程》
前端·javascript·webpack·typescript·node.js·es6
lovepenny4 小时前
Failed to resolve entry for package "js-demo-tools". The package may have ......
前端·npm
超凌4 小时前
threejs 创建了10w条THREE.Line,销毁数据,等待了10秒
前端