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

示例

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

特殊情况请自行修改函数

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));
相关推荐
胡桃夹夹子5 分钟前
【前端优化】vue2 webpack4项目升级webpack5,大大提升运行速度
前端·javascript·vue.js·webpack·性能优化
Stringzhua10 分钟前
JavaScript【7】BOM模型
开发语言·前端·javascript
DT——18 分钟前
ECMAScript 2018(ES2018):异步编程与正则表达式的深度进化
开发语言·javascript·ecmascript
阿幸软件杂货间26 分钟前
谷歌浏览器(Google Chrome)136.0.7103.93便携增强版|Win中文|安装教程
前端·chrome
双叶83632 分钟前
(C语言)超市管理系统 (正式版)(指针)(数据结构)(清屏操作)(文件读写)(网页版预告)(html)(js)(json)
c语言·javascript·数据结构·html·json
繁依Fanyi1 小时前
Animaster:一次由 CodeBuddy 主导的 CSS 动画编辑器诞生记
android·前端·css·编辑器·codebuddy首席试玩官
想起你的日子1 小时前
Android studio 实现弹出表单编辑界面
java·前端·android studio
LuckyLay2 小时前
Vue百日学习计划Day9-15天详细计划-Gemini版
前端·vue.js·学习
weifont6 小时前
聊一聊Electron中Chromium多进程架构
javascript·架构·electron
大得3696 小时前
electron结合vue,直接访问静态文件如何跳转访问路径
javascript·vue.js·electron