Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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();
about 4 years ago · Juan Pablo Isaza Relatório

0

Instead of parsing the day to an integer and looping that way, use the built-in momentjs function subtract to walk back the 31 days from the current date, then loop forward using the add function in momentjs.

const DAYS = () => {
  const days = []
  const dateStart = moment().subtract(31, 'days')
  const dateEnd = moment()
  while (dateEnd.diff(dateStart, 'days') >= 0) {
    days.push(dateStart.format('MM-DD'));
    dateStart.add(1, 'days')
  }
  return days;
}
console.log(DAYS())
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda