JavaScript如何获取当前日期到指定结束日期间所有指定月中日的列表
实现思路
通过逐月生成目标日期,统一用日期大小比较完成规则校验,无需复杂分支判断,同时兼容部分月份无对应目标日的边界场景。
完整代码
function getValidDates(targetDay, endDate) { const result = []; const now = new Date(); // 初始化遍历的年、月,JS中月份从0开始计数 let currentYear = now.getFullYear(); let currentMonth = now.getMonth(); while (true) { // 生成当月目标日 const candidate = new Date(currentYear, currentMonth, targetDay); // 超出结束日期直接终止循环 if (candidate > endDate) break; // 校验规则: // 1. 目标日确实是当月对应日期(过滤2月无30号、小月无31号这类自动进位的无效日期) // 2. 目标日晚于等于当前日期(满足规则1) // 3. 目标日早于等于结束日期(满足规则2) if (candidate.getDate() === targetDay && candidate >= now && candidate <= endDate) { // 可根据需要修改日期输出格式 result.push(candidate.toLocaleDateString()); } // 月份+1,JS会自动处理跨年逻辑 currentMonth++; } return result; }
调用测试
// 示例场景:目标日1号,结束日期2021/12/10,当前日期假设为2021/9/20 const res = getValidDates(1, new Date(2021, 11, 10)); console.log(res); // 输出符合预期:['10/1/2021', '11/1/2021', '12/1/2021']
内容的提问来源于stack exchange,提问作者Kayo
相关产品推荐
相关产品推荐

