网站首页 > 技术文章 正文
示例
传参数年、月,返回包含当月的所有周数、及周的起止日期,支持跨月
特殊情况请自行修改函数
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));
猜你喜欢
- 2025-07-06 为什么前端大佬都推荐用 performance.now() 而非 Date.now()?
- 2025-07-06 实战分享:邀请有礼产品怎么做?(邀请有礼活动)
- 2025-07-06 揭秘:视频播放网站如何精准记录用户观看进度
- 2025-07-06 第七篇 前端基础十问,看看你是否真的掌握扎实?
- 2025-07-06 下单预约送货时间功能设计及思路(预约送货怎么说)
- 2025-07-06 每天一个 Python 库:datetime 模块全攻略,时间操作太丝滑!
- 2025-07-06 前端代码更新,如何优雅地通知用户刷新页面?
- 2024-10-09 JS Date对象的妙用:如何更优雅的计算时间差?
- 2024-10-09 从零开始的前端请求之旅 从零开始学前端开发
- 2024-10-09 如何在上班时间利用终端控制台摸鱼??????
你 发表评论:
欢迎- 593℃几个Oracle空值处理函数 oracle处理null值的函数
- 586℃Oracle分析函数之Lag和Lead()使用
- 574℃0497-如何将Kerberos的CDH6.1从Oracle JDK 1.8迁移至OpenJDK 1.8
- 571℃Oracle数据库的单、多行函数 oracle执行多个sql语句
- 567℃Oracle 12c PDB迁移(一) oracle迁移到oceanbase
- 559℃【数据统计分析】详解Oracle分组函数之CUBE
- 546℃最佳实践 | 提效 47 倍,制造业生产 Oracle 迁移替换
- 540℃Oracle有哪些常见的函数? oracle中常用的函数
- 最近发表
- 标签列表
-
- 前端设计模式 (75)
- 前端性能优化 (51)
- 前端模板 (66)
- 前端跨域 (52)
- 前端缓存 (63)
- 前端react (48)
- 前端aes加密 (58)
- 前端脚手架 (56)
- 前端md5加密 (54)
- 前端路由 (61)
- 前端数组 (73)
- 前端js面试题 (50)
- 前端定时器 (59)
- 前端懒加载 (49)
- 前端获取当前时间 (50)
- Oracle RAC (73)
- oracle恢复 (76)
- oracle 删除表 (48)
- oracle 用户名 (74)
- oracle 工具 (55)
- oracle 内存 (50)
- oracle 导出表 (57)
- oracle 中文 (51)
- oracle的函数 (57)
- 前端调试 (52)
本文暂时没有评论,来添加一个吧(●'◡'●)