MomentJS - 获取日期范围给出一个月中的特定日期

MomentJS - Get date range give a specific day of the month

给定 5 月的第几天,您如何最好地获得 last/this 月 5 号和下一个 5 号之间的日期范围?

// given today is May 24 2021
// should return May 5 - June 5
function getDateRange(selectedDay) {
  const today = moment()
  let previous, next
  if (today.date() >= selectedDay) {
    previous = today.clone().set('date', selectedDay)
    next = today.clone().add(1, 'months').set('date', selectedDay)
  }
  else {
    previous = today.clone().subtract(1, 'months').set('date', selectedDay)
    next = today.clone().set('date', selectedDay)
  }

  return [ previous, next ]
}

除了当月不存在所选日期(即 31 日)外,大多数情况下都有效。

例如,如果今天的日期是 Feb 15, 2021 并且 selectedDay31,函数应该 return Jan 31 - Feb 28.

有人对此有一个优雅的解决方案吗?

我稍微编辑了您的代码并插入了一个函数来确定该月的最大日期。

// To force a date I inserted a initDate like parameters, remove it if it's unnecessary
function getDateRange(selectedDay, initDate) {
  const today = moment(initDate);

  let previous;
  let next;

  if (today.date() >= selectedDay) {
    previous = moment(today).startOf('month');
    next = moment(today).add(1, 'month').startOf('month');
  } else {
    previous = moment(today).subtract(1, 'months');
    next = moment(today);
  }

  previous = limiter(previous, selectedDay); // this function get the max date of the month
  next = limiter(next, selectedDay);

  return [previous, next];
}

function limiter(dateToLimit, selectedDay) {
  if (moment(dateToLimit).endOf('month').isBefore(moment(dateToLimit).date(selectedDay))) dateToLimit = moment(dateToLimit).endOf('month');
  else dateToLimit = moment(dateToLimit).date(selectedDay);

  return dateToLimit;
}

console.log(getDateRange(31, '2021-02-15'));
console.log(getDateRange(31, '2021-03-15'));
console.log(getDateRange(13, '2021-02-15'));
console.log(getDateRange(13, '2021-09-15'));
console.log(getDateRange(26, '2021-09-15'));
console.log(getDateRange(26, '2021-09-27'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.25.1/moment.min.js"></script>