Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
Date () en js no cambia los días correctamente

Quiero aumentar y disminuir los días en una fecha sin cambiar otras partes de la fecha. Por ejemplo, cuando tengo:

  • 31 de diciembre de 2021 -> agregar un día -> 01 de diciembre de 2021, o
  • 01 diciembre 2021 -> restar un día -> 31 diciembre 2021

A continuación, está mi código de día de aumento. Funciona bien y obtengo lo que quiero:

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

Mi código de día de disminución no funciona y obtengo 31 December 2021 después 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);

¿Como arreglarlo?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Esto sucede porque noviembre no tiene 31 días, por lo que cuando retrocedes un día desde el 1 de noviembre, obtienes el 31 de octubre. Luego cambia el mes para que sea el 31 de noviembre, pero JavaScript lo interpreta como 30 de noviembre + 1 día = 1 de diciembre.

Para evitar esto, realice una verificación antes de restar un día: si la fecha es 1, primero agregue un mes y luego deje que ocurra la resta de 1 día:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!