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