首页 > 解决方案 > 两个日期之间存在的所有月份的列表,包括日期之间的差异小于 30 天的情况

问题描述

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

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

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

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

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

我在这里尝试了示例JavaScript:获取两个日期之间的所有月份?但是如果天数 <30,momentjs 不会给出 endMonth

标签: javascriptmomentjs

解决方案


我认为这是获得您正在寻找的结果的好解决方案

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>


推荐阅读