- 首先将开始日期和结束日期转换为 Date 对象。
- 创建一个空数组用于存储分段后的日期范围。
- 使用循环按月份递增,每次递增将当前月份的开始日期和结束日期添加到数组中。
- 在每次循环时,如果当前月份是结束日期所在的月份,则结束日期改为结束日期的最后一天,以避免超出结束日期范围。
- 返回分段后的日期范围数组。
function getMonthRanges(startDate, endDate) {
startDate = new Date(startDate);
endDate = new Date(endDate);
const ranges = [];
for (let date = startDate; date <= endDate; date.setMonth(date.getMonth() + 1)) {
const start = new Date(date.getFullYear(), date.getMonth(), 1);
const end = new Date(date.getFullYear(), date.getMonth() + 1, 0);
if (end > endDate) {
end.setDate(endDate.getDate());
}
ranges.push({ startDate: formatDate(start), endDate: formatDate(end) });
}
return ranges;
}
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}`;
}
const ranges = getMonthRanges('2022-01-15', '2022-10-20');
console.log(ranges);
[ { startDate: '2022-01-15', endDate: '2022-01-31' }, { startDate: '2022-02-01', endDate: '2022-02-28' }, { startDate: '2022-03-01', endDate: '2022-03-31' }, { startDate: '2022-04-01', endDate: '2022-04-30' }, { startDate: '2022-05-01', endDate: '2022-05-31' }, { startDate: '2022-06-01', endDate: '2022-06-30' }, { startDate: '2022-07-01', endDate: '2022-07-31' }, { startDate: '2022-08-01', endDate: '2022-08-31' }, { startDate: '2022-09-01', endDate: '2022-09-30' }, { startDate: '2022-10-01', endDate: '2022-10-20' }]