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

How do I create an array of the previous 31 days using Moment.js?

Using moment.js I’m trying to generate an array of the previous 31 days in a particular moment.js format. This is my current code:

let labels = [];
const popArray = () => {
    let nowMonth: any = moment().format('D');
    let newMonth = parseInt(nowMonth);
    let startMonth = newMonth - 31;
    for(let i = startMonth; i < newMonth; i++){
        labels.push(moment().day(i).format('MM-DD'));
    }
    console.log(labels)
}
popArray();

When I run this code I get an array of 31 days, the first being "11-10" and the last being "12-10". Why is this? I’ve tried different configurations where startMonth is "-31" and newMonth is "0" but it still doesn’t work.

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

>Solution :

You can simply using the subtract method like this:

let labels = [];
    const popArray = () => {
        for (let i = 0; i <= 31; i++){
            labels.push(moment().subtract(i, "days").format('MM-DD'))
        }
        console.log(labels)
    }
popArray();
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