Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda