1

有没有一种有效的方法来计算日期范围内按月分组的天数?

例如,给定日期范围为 2020-01-30 到 2020-02-03,输出将是{ 'January': 2, 'February': 3 }.

4

1 回答 1

1

我认为除了计算之外没有更有效的方法。

const firstDateToPass = { year: 2020, month: 1, day: 26 };
const secondDateToPass = { year: 2020, month: 1, day: 29 };

const getCountOfDaysGroupedByMonth = (startDate, endDate) => {
  const firstMonthDateTime = DateTime.fromObject(startDate);
  const secondMonthDateTime = DateTime.fromObject(endDate);
  if (firstMonthDateTime.month === secondMonthDateTime.month) {
    // In same month
    // Return difference in days
    return {
      [firstMonthDateTime.monthLong]: secondMonthDateTime.day - firstMonthDateTime.day
    }
  }
}

console.log(getCountOfDaysGroupedByMonth(firstDateToPass, secondDateToPass)) // { January: 3 }

您只需要涵盖跨越多个月的案件,但我现在将把这个问题留给您解决?

于 2020-09-22T19:23:25.610 回答