Home > Net >  Generate Array of months with moment - Reactjs
Generate Array of months with moment - Reactjs

Time:05-04

My goal is to generate an array of months from today date month to 1 year in the past. So it will look like this

(based on today date 04-05-2022)

const months = ['Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May']

My current try to generate my array :

  useEffect(() => {
        const months = []
        const dateStart = moment()
        const dateEnd = moment().subtract(11, 'month')
        while (dateEnd.diff(dateStart, 'months') >= 0) {
            months.push(dateStart.format('MMM'))
            dateStart.add(1, 'month')
        }

        console.log(months)
        return months

   },[])

Normally i think it has to be ok , but in my output i get an empty Array . Does somebody know what am i doing wrong ? Thanks for the help.

CodePudding user response:

Instead off using diff(), why not use isBefore()

Also, you're adding 1 month to dateStart but that needs to be dateEnd

const months = []
const dateStart = moment()
const dateEnd = moment().subtract(11, 'month')

while (dateEnd.isBefore(dateStart, 'day')) {
    months.push(dateEnd.format('MMM'))
    dateEnd.add(1, 'month')
}
months.push(dateEnd.format('MMM'))

console.log(months);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>

[
  "Jun",
  "Jul",
  "Aug",
  "Sep",
  "Oct",
  "Nov",
  "Dec",
  "Jan",
  "Feb",
  "Mar",
  "Apr",
  "May"
]
  • Related