I want to increase and decrease days in a date without changing other parts of the date. For example, when I have:
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?
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);