JS获取指定月份含日期/星期/月份的完整周数组方法
改造后函数实现
改造后的函数完全兼容原有入参规则,同时满足跨月日期补全、单周全量日期返回的要求,返回的每个日期对象均包含要求的三个字段。
核心逻辑说明
- 入参保持不变:第一个参数传月份(取值范围0-11,0代表1月、11代表12月),第二个参数传4位年份数值
- 周规则默认以周一为每周起始、周日为每周结束,可根据需要调整代码内周起始偏移量
- 自动补全跨月日期:月初首周自动填充上月末尾日期凑齐全周,月末尾周自动填充下月开头日期凑齐全周
- 单条日期数据字段:
date:数字类型,对应日期的日号,例如1、31month:字符串类型,对应日期所属月份的中文名称,例如1月、12月day:字符串类型,对应日期的星期中文名称,例如周一、周日
完整代码
function getFullWeeksStartAndEndInMonth(month, year) { // 中文映射配置,可根据需要替换为英文或其他格式 const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']; const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; // 周起始配置:0为周日起始,1为周一起始 const weekStart = 1; // 生成当月第一天日期对象 const firstDayOfMonth = new Date(year, month, 1); // 计算首周需要向前补的天数 const offsetDays = (firstDayOfMonth.getDay() - weekStart + 7) % 7; // 计算日历渲染的起始日期(补全上月日期后的首周第一天) const calendarStart = new Date(firstDayOfMonth); calendarStart.setDate(1 - offsetDays); const weeks = []; // 最多生成6周数据即可覆盖所有月份的完整周展示 for (let weekIndex = 0; weekIndex < 6; weekIndex++) { const currentWeek = []; for (let dayIndex = 0; dayIndex < 7; dayIndex++) { const currentDate = new Date(calendarStart); currentDate.setDate(calendarStart.getDate() + weekIndex * 7 + dayIndex); currentWeek.push({ date: currentDate.getDate(), month: monthNames[currentDate.getMonth()], day: dayNames[currentDate.getDay()] }); // 超过当月最后一天所在周后停止生成 if ( currentDate.getMonth() > month && currentDate.getDay() === (weekStart + 6) % 7 ) { weeks.push(currentWeek); return weeks; } } weeks.push(currentWeek); } return weeks; }
返回格式示例
以调用getFullWeeksStartAndEndInMonth(2, 2024)(查询2024年3月周数据,3月1日为周五)为例,首周返回数据如下:
[ [ {date: 26, month: '2月', day: '周一'}, {date: 27, month: '2月', day: '周二'}, {date: 28, month: '2月', day: '周三'}, {date: 29, month: '2月', day: '周四'}, {date: 1, month: '3月', day: '周五'}, {date: 2, month: '3月', day: '周六'}, {date: 3, month: '3月', day: '周日'} ], // 后续周数据按相同结构排列 ]
如果需要调整周起始规则,修改代码内
weekStart常量即可:设为0时以周日为每周第一天,设为1时以周一为每周第一天。月份、星期的显示文本也可以直接修改映射数组自定义。
内容的提问来源于stack exchange,提问作者hamzasgd
相关产品推荐
相关产品推荐

