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

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

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 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