Las fechas van a un mes a cada lado y luego se atascan en bucles. A partir de junio, irá bien hasta finales de julio o principios de mayo, pero luego volverá al final/inicio de esos meses en lugar de ir más allá. globalDate es un estado React definido const [globalDate, setGlobalDate] = useState(new Date());
Fragmento de código:
//decreasing const newDate = new Date(); newDate.setDate(globalDate.getDate() - 1); if (globalDate.getMonth() !== newDate.getMonth()) { newDate.setMonth(globalDate.getMonth()); } if (globalDate.getDate() <= 1) { newDate.setMonth(globalDate.getMonth() - 1); newDate.setDate(daysInMonth[newDate.getMonth()]); } setGlobalDate(newDate); //increasing const newDate = new Date(); newDate.setDate(globalDate.getDate() + 1); if (globalDate.getMonth() !== newDate.getMonth()) { newDate.setMonth(globalDate.getMonth()); } if (globalDate.getDate() >= daysInMonth[globalDate.getMonth()]) { newDate.setMonth(globalDate.getMonth() + 1); newDate.setDate(1); } setGlobalDate(newDate);Fuente de página completa: https://github.com/Westsi/thynkr/blob/master/frontend/web/js/src/Planner.js
El problema en el primer bloque de código ("decreciente") ocurre cuando se newDate.setMonth() cuando newDate tiene una fecha que es el último día del mes y el mes anterior tiene menos días. Entonces, por ejemplo, sucede cuando newDate es el 31 de mayo en el momento en que se realiza esta llamada a setMonth . Esa llamada ajustará la fecha al 31 de abril, pero esa fecha se traduce automáticamente al 1 de mayo, ya que abril solo tiene 30 días, por lo que te quedas atascado en el mes de mayo.
Para evitar este tipo de problemas, simplemente comience con globalDate inmediatamente y reste o agregue un día. Eso es todo. El desbordamiento en un mes siguiente/anterior es algo que JavaScript ya trata automáticamente. Entonces, en lugar de intentar hacer esto usted mismo (y tener problemas), deje que JavaScript lo haga por usted:
Lógica decreciente:
const newDate = new Date(globalDate); // starting point! newDate.setDate(globalDate.getDate() - 1); // month overflow happens automatically! setGlobalDate(newDate); // That's it!Lógica creciente:
const newDate = new Date(globalDate); // starting point! newDate.setDate(globalDate.getDate() + 1); // month overflow happens automatically! setGlobalDate(newDate); // That's it!