Как получить список всех месяцев с текущего месяца до месяца в прошлом, используя момент. js - PullRequest
1 голос
/ 30 мая 2020

Я пытаюсь создать список месяцев, начиная с апреля 2020 года и заканчивая месяцем в прошлом (октябрь 2019 года), используя момент . js.

const start = moment().startOf('month')
const startMonth = moment('10-01-2019', 'MM-DD-YYYY').format('MMMM YYYY')
const month = moment().startOf('month').format('MM')
for (let i = 0; i < month; i++) {
  const m = start.subtract(1, 'month').format('MMMM YYYY')
  if (m === startMonth) {
    break;
  }
  console.log(m)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script>

В итоге я получаю всего 5 месяцев. Может ли кто-нибудь помочь?

Ответы [ 2 ]

3 голосов
/ 30 мая 2020

Использование isSameOrBefore()

const start = moment().startOf('month')
const end = moment('11-11-2019', 'MM-DD-YYYY')

while (end.isSameOrBefore(start, 'month')) {
  console.log(start.format('MMMM YYYY'))
  start.subtract(1, 'month')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script>

Исключить текущий месяц

const start = moment().startOf('month')
const end = moment('11-11-2019', 'MM-DD-YYYY')

while (end.isBefore(start, 'month')) {
  start.subtract(1, 'month')
  console.log(start.format('MMMM YYYY'))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script>
1 голос
/ 30 мая 2020

Что-то вроде этого?

const start = moment().startOf('month')
const end = moment('10-01-2018', 'MM-DD-YYYY')

let results = []
let current = start
while (current.format('MMMM YYYY') !== end.format('MMMM YYYY')) {
  results.push(current.format('MMMM YYYY'))
  current = current.subtract(1, 'month')
}
// need to add current one last time because the loop will have ended when it is equal to the end date, and will not have added it
results.push(current.format('MMMM YYYY'))

console.log(results)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script>
...