Home > database >  Moment: how to get month array for a date range
Moment: how to get month array for a date range

Time:05-28

let startDate = '2022/01/1';
let endDate = '2022/05/31'

Does moment have the function to get the following month array from the above give date range??

[
  2022/01, 2022/02, 2022/03, 2022/04, 2022/05
]

Thanks a lot.

CodePudding user response:

You can use isSameOrBefore with add methods to achieve this:

const monthsBetweenDates = (startDate, endDate) => {
    const now = startDate, dates = [];
      
    while (now.isSameOrBefore(endDate)) {
          dates.push(now.format('YYYY/MM'));
          now.add(1, 'months');
    }
    return dates;
}

const fromDate = moment();
const toDate   = moment().add(6, 'months');
const results = monthsBetweenDates(fromDate, toDate);
console.log(results);
  • Related