js根据开始结束日期进行月度分段?

269 阅读1分钟
  1. 首先将开始日期和结束日期转换为 Date 对象。
  2. 创建一个空数组用于存储分段后的日期范围。
  3. 使用循环按月份递增,每次递增将当前月份的开始日期和结束日期添加到数组中。
  4. 在每次循环时,如果当前月份是结束日期所在的月份,则结束日期改为结束日期的最后一天,以避免超出结束日期范围。
  5. 返回分段后的日期范围数组。
function getMonthRanges(startDate, endDate) {
  // 将日期字符串转换为 Date 对象
  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' }]