JS如何获取两个日期间的所有月份,含间隔不足30天场景
JS 获取两个日期之间包含的所有月份列表解决方案
问题原因
之前的常规实现多通过日期间隔的月份差值计算结果,使用Moment.js时diff('month')方法会返回两个日期之间的整月差,间隔不足30天时返回0,导致结束月份被遗漏。
核心解决思路
不从时间间隔维度计算,直接从开始日期的月份逐个遍历,只要当前日期的年月不大于结束日期的年月,就将对应月份加入结果集,天然覆盖跨月不足30天的场景。
方案1:Moment.js 实现
function getIncludedMonths(startDateStr, endDateStr) { const start = moment(startDateStr); const end = moment(endDateStr); const result = []; // 遍历直到当前年月超过结束日期的年月 while (start.isSameOrBefore(end, 'month')) { result.push(start.month() + 1); // moment月份为0基,转1基 start.add(1, 'month'); } return result; }
测试用例验证
getIncludedMonths('2021-04-25', '2021-05-12')返回[4,5]getIncludedMonths('2021-04-25', '2021-08-12')返回[4,5,6,7,8]getIncludedMonths('2021-10-25', '2022-02-12')返回[10,11,12,1,2]
方案2:原生JS实现(无需第三方库)
function getIncludedMonths(startDateStr, endDateStr) { const start = new Date(startDateStr); const end = new Date(endDateStr); const result = []; // 提取结束日期的年、月用于比较 const endYear = end.getFullYear(); const endMonth = end.getMonth(); while (true) { const currentYear = start.getFullYear(); const currentMonth = start.getMonth(); // 加入当前月份(转1基) result.push(currentMonth + 1); // 已经到结束月份则跳出循环 if (currentYear === endYear && currentMonth === endMonth) { break; } // 月份加1,Date对象会自动处理年份进位 start.setMonth(currentMonth + 1); } return result; }
内容的提问来源于stack exchange,提问作者Priyanka
相关产品推荐
相关产品推荐

