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

132
Visualizações
JS problem with the month of February in non-leap months

I am implementing a simple calendar, but i have a problem with all non-leap fever months.

If you click on next until February 2023, March is shown, if you advance until 2024 (which is a leap), everything works, how can I solve?

let nav = 0;

let test = () => {
  const dt = new Date();
  dt.setMonth(new Date().getMonth() + nav);
  const day = dt.getDate();
  const month = dt.getMonth();
  const year = dt.getFullYear();
  const monthName = `${dt.toLocaleDateString("en", { month: "long" })} ${year}`;
  
  document.getElementById('feedBack').innerHTML = 'Nav: ' + nav + ' - Day: ' + 1 + ' - Month: ' + month + ' ( <b>' + monthName + '</b> ) - Year: ' + year;
}

test();
#feedBack {margin-top:10px}
<button onclick="nav--;test()">Prev</button>
<button onclick="nav=0;test();">Current</button>
<button onclick="nav++;test();">Next</button>

<div id="feedBack"></div>

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

0

If you wait for two days the problem will be solved hehe (today is 29/06, you are iterating over, 29/07, 29/08, etc.).

Or you could change day of the month object before incrementing the month.

let nav = 0;

let test = () => {
  const dt = new Date();
  dt.setDate(1); // this will move to the first day of the current month
  dt.setMonth(new Date().getMonth() + nav);
  const month = dt.getMonth();
  const year = dt.getFullYear();
  const monthName = `${dt.toLocaleDateString("en", { month: "long" })} ${year}`;
  
  document.getElementById('feedBack').innerHTML = 'Nav: ' + nav + ' - Day: ' + 1 + ' - Month: ' + month + ' ( <b>' + monthName + '</b> ) - Year: ' + year;
}

test();
#feedBack {margin-top:10px}
<button onclick="nav--;test()">Prev</button>
<button onclick="nav=0;test();">Current</button>
<button onclick="nav++;test();">Next</button>

<div id="feedBack"></div>

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