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

示例

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

特殊情况请自行修改函数

console.log(getWeeksInMonth(2024, 9));

返回如下
在这里插入图片描述

源码

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

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值