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

236
Visualizações
Get previous date in JavaScript

I am trying to get the date before a given date in JavaScript. This is what I've come up with.

function getPreviousDay(year, month, day) {
    const date = new Date(year, month - 1, day); // the month is 0-indexed
    date.setDate(date.getDate() - 1);

    console.log(`${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`);
}

getPreviousDay(2016, 9, 30); // 2016-8-29, Expected output: 2016-9-29
getPreviousDay(2016, 10, 1); // 2016-8-30, Expected output: 2016-9-30

Why doesn't it work as expected? Thank you in advance!

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

0

You make month - 1, when initializing the date, but should be a month.

about 4 years ago · Juan Pablo Isaza Relatório

0

As you said, months, in js date object, are 0-indexed.

So you do very good to substract one from the month, when creating the date object.

Your problem is, that you don't add back that one month when showing the date object :

   console.log(`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`);
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