Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate Array of months with moment – Reactjs

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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.

>Solution :

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"
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading