首页 > 解决方案 > 如何在 MomentJS 中获取上个月、过去三个月的天数列表

问题描述

使用moment().subtract(1, 'days').format("YYYY-MM-DD")i 可以获得当前日期的最后 x 天。那么我怎样才能得到上个月或过去三个月的所有天数..?

标签: javascriptmomentjs

解决方案


这是获取当月天数的方法:

const numberOfDaysInCurrentMonth = moment().daysInMonth();

因此,您可以通过以下方式获取上个月的天数:

const numberOfDaysInLastMonth = moment().subtract(1, 'months').daysInMonth();

现在你需要上个月的开始:

const startOfLastMonth = moment().subtract(1, 'months').startOf('month');

您已准备好开始迭代并构建您的列表:

const numberOfDaysInLastMonth = moment().subtract(1, 'months').daysInMonth();
const startOfLastMonth = moment().subtract(1, 'months').startOf('month');

for (let i = 0; i < numberOfDaysInLastMonth; i = i + 1) {
  console.log(startOfLastMonth.format('YYYY MMM DD'));
  startOfLastMonth.add(1, 'days');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>

对于过去 3 个月,只需更改您的开始日期和天数:

const numberOfDaysInLast3Months = moment().subtract(1, 'months').daysInMonth() +
  moment().subtract(2, 'months').daysInMonth() +
  moment().subtract(3, 'months').daysInMonth();
const startDate = moment().subtract(3, 'months').startOf('month');

for (let i = 0; i < numberOfDaysInLast3Months; i = i + 1) {
  console.log(startDate.format('YYYY MMM DD'));
  startDate.add(1, 'days');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>


推荐阅读