两个日期之间存在的所有月份的列表,包括日期之间的数字差异小于 30 天的情况

List of all the months that exists between the 2 dates including case when num difference between dates is less than 30 days

我想获取 JS 中两个日期之间存在的所有月份的列表。例如:

'2021-04-25' 到 '2021-05-12' 应该 return [4,5] // case when num difference between dates is less than 30 days

'2021-04-25' 到 '2021-08-12' 应该 return [4,5,6,7,8]

'2021-10-25' 到 '2022-02-12' 应该 return [10,11,12,1,2]

以下代码有效,但没有给出“2021-04-25”到“2021-05-12”的正确结果。它 return 只有 [4]

我尝试了示例 但如果天数 <30

,momentjs 不会给出 endMonth

我认为这是获得所需结果的好解决方案

function getMonths(start, end) {
  start = moment(start).startOf('month');
  end = moment(end).startOf('month');

  if (start.isAfter(end))[start, end] = [end, start]; // This is only for order the dates

  const months = [];
  while (start.isSameOrBefore(end)) {
    months.push(start.month() + 1);
    start.add(1, 'months');
  }

  return months;
}

console.log(getMonths('2021-04-25', '2021-05-12'));
console.log(getMonths('2021-04-25', '2021-08-12'));
console.log(getMonths('2021-10-25', '2022-02-12'));
console.log(getMonths('2021-04-25', '2022-02-12'));
console.log(getMonths('2021-06-26', '2020-02-12'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

momentjs site 上他们说:“我们现在普遍认为 Moment 是一个处于维护模式的遗留项目。它没有死,但确实已经完成了。” 您可以使用另一个图书馆作为结束日期。

这是一个示例,其逻辑与 AlTheLazyMonkey 提出的 date-fns

相同
  import {
  addMonths,
  getMonth,
  isBefore,
  isEqual,
  startOfMonth
} from "date-fns";

let start = "2021-06-15";
let end = "2021-12-26";

const isSameOrBefore = (start, end) => {
  const result = (isBefore(start, end) || isEqual(start, end)) ?
    true :
    false
  return result
};

const getArrayOfMonths = (start, end) => {
  let startDate = startOfMonth(new Date(start));
  let endDate = startOfMonth(new Date(end));
  const arrayOfMonths = [];
  if (isBefore(endDate, startDate)) {
    console.log("End date must be greated than start date.");
  }

  while (isSameOrBefore(startDate, endDate)) {
    arrayOfMonths.push(getMonth(startDate) + 1);
    startDate = addMonths(startDate, 1);
  }
  return arrayOfMonths;
};

console.log(getArrayOfMonths(start, end));
console.log(getArrayOfMonths("2021-02-15", "2021-9-15"));