Estoy implementando un calendario simple, pero tengo un problema con todos los meses sin fiebre.
Si le das a next hasta febrero 2023 se muestra marzo, si avanzas hasta 2024 (que es un salto) todo funciona, como lo puedo solucionar?
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>Si esperas dos días se soluciona el problema jeje (hoy es 29/06, estás iterando sobre, 29/07, 29/08, etc.).
O puede cambiar el objeto del día del mes antes de incrementar el mes.
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>