JS实现根据当前日期划分月份上下半月并返回对应工作日列表
实现方案
核心规则对齐
- 半月划分:上半月取当月15日及之前的最后两个完整工作周(周一至周五),下半月取当月16日及之后的前两个完整工作周(周一至周五),和示例输出完全匹配
- 日期统一格式为
YYYY-MM-DD,月、日自动补前导零 - 若需要过滤法定节假日,可在现有逻辑基础上追加节假日日期黑名单判断
原生JS实现(无第三方依赖)
function getHalfMonthWorkdates(current = new Date()) { const year = current.getFullYear(); const month = current.getMonth(); const curDay = current.getDate(); const result = []; if (curDay <= 15) { // 上半月:定位到15号或之前最近的周五作为结束点 let endDate = new Date(year, month, 15); while (endDate.getDay() !== 5) { endDate.setDate(endDate.getDate() - 1); } // 从结束点往前遍历,收集满10个工作日 let temp = new Date(endDate); let workdayCount = 0; while (workdayCount < 10) { const day = temp.getDay(); if (day !== 0 && day !== 6) { const m = String(temp.getMonth() + 1).padStart(2, '0'); const d = String(temp.getDate()).padStart(2, '0'); result.unshift(`${temp.getFullYear()}-${m}-${d}`); workdayCount++; } temp.setDate(temp.getDate() - 1); } } else { // 下半月:定位到16号或之后最近的周一作为起始点 let startDate = new Date(year, month, 16); while (startDate.getDay() !== 1) { startDate.setDate(startDate.getDate() + 1); } // 从起始点往后遍历,收集满10个工作日 let temp = new Date(startDate); let workdayCount = 0; while (workdayCount < 10) { const day = temp.getDay(); if (day !== 0 && day !== 6) { const m = String(temp.getMonth() + 1).padStart(2, '0'); const d = String(temp.getDate()).padStart(2, '0'); result.push(`${temp.getFullYear()}-${m}-${d}`); workdayCount++; } temp.setDate(temp.getDate() + 1); } } return result; } // 测试用例1:传入2022-07-06,返回上半月结果 const firstHalfWeekdates = getHalfMonthWorkdates(new Date(2022, 6, 6)); // 输出:['2022-07-04', '2022-07-05', '2022-07-06', '2022-07-07', '2022-07-08', '2022-07-11', '2022-07-12', '2022-07-13', '2022-07-14', '2022-07-15'] 与预期完全一致 // 测试用例2:传入2022-07-18,返回下半月结果 const secondHalfWeekdates = getHalfMonthWorkdates(new Date(2022, 6, 18)); // 输出:['2022-07-18', '2022-07-19', '2022-07-20', '2022-07-21', '2022-07-22', '2022-07-25', '2022-07-26', '2022-07-27', '2022-07-28', '2022-07-29'] 与预期完全一致
dayjs轻量库实现
如果项目已引入dayjs,可以用更简洁的写法实现:
import dayjs from 'dayjs'; function getHalfMonthWorkdates(current = dayjs()) { const result = []; if (current.date() <= 15) { let end = current.date(15); // 调整到15号前最近的周五 while (end.day() !== 5) end = end.subtract(1, 'day'); let temp = end; let count = 0; while (count < 10) { if (temp.day() !== 0 && temp.day() !==6) { result.unshift(temp.format('YYYY-MM-DD')); count++; } temp = temp.subtract(1, 'day'); } } else { let start = current.date(16); // 调整到16号后最近的周一 while (start.day() !== 1) start = start.add(1, 'day'); let temp = start; let count = 0; while (count < 10) { if (temp.day() !==0 && temp.day() !==6) { result.push(temp.format('YYYY-MM-DD')); count++; } temp = temp.add(1, 'day'); } } return result; }
内容的提问来源于stack exchange,提问作者JustJules
相关产品推荐
相关产品推荐

