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

203
Visualizações
Date() in js doesn't switch days correctly

I want to increase and decrease days in a date without changing other parts of the date. For example, when I have:

  • 31 December 2021 -> add one day -> 01 December 2021, or
  • 01 December 2021 -> subtract one day -> 31 December 2021

Below, is my increase day code. It works fine and I get what I want:

let cur_date = new Date();

setInterval(() => {
  let curMonth = cur_date.getMonth();
  cur_date.setDate(cur_date.getDate() + 1);
  if (cur_date.getMonth() !== curMonth) {
    cur_date.setMonth(curMonth);
  }
  console.log(cur_date.toLocaleString());
}, 1000);

My decrease day code does not work and I get 31 December 2021 after 01 November 2021:

let cur_date = new Date();

setInterval(() => {
  let curMonth = cur_date.getMonth();
  cur_date.setDate(cur_date.getDate() - 1);
  if (cur_date.getMonth() !== curMonth) {
    cur_date.setMonth(curMonth);
  }
  console.log(cur_date.toLocaleString());
}, 1000);

How to fix it?

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

0

This happens because November does not have 31 days, and so when you go one day back from 1 November, you get 31 October. Then you change the month so it would be 31 November, but JavaScript interprets that as 30 November + 1 day = 1 December.

To avoid this, perform a check before subtracting one day: if the date is 1, then first add a month, and then let the subtraction of 1 day happen:

let cur_date = new Date();

setInterval(() => {
  let curMonth = cur_date.getMonth();
  if (cur_date.getDate() === 1) { // Do the check here, before subtracting 1 day
    cur_date.setMonth(curMonth + 1); // Go temporary to next month
  }
  cur_date.setDate(cur_date.getDate() - 1);
  console.log(cur_date.toLocaleString());
}, 1000);

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