How can I get the next Monday in JavaScript? I can\'t find anything of this in the internet and I have also tried a lot of codes and understanding of this but I can\'t reall
If the actual day of the week you want is variable (Sunday, Thursday, ...) and you want a choice whether today could be a possible match or not, and it might be that you want to start with another date (instead of today), then this function may be useful:
function getNextDayOfTheWeek(dayName, excludeToday = true, refDate = new Date()) {
const dayOfWeek = ["sun","mon","tue","wed","thu","fri","sat"]
.indexOf(dayName.slice(0,3).toLowerCase());
if (dayOfWeek < 0) return;
refDate.setHours(0,0,0,0);
refDate.setDate(refDate.getDate() + +!!excludeToday +
(dayOfWeek + 7 - refDate.getDay() - +!!excludeToday) % 7);
return refDate;
}
console.log("Next is: " + getNextDayOfTheWeek("Wednesday", false));
This will give next Monday if today is Monday
var d = new Date();
d.setDate(d.getDate() + (7-d.getDay())%7+1);
This will result in today if today is Monday
var d = new Date();
d.setDate(d.getDate() + ((7-d.getDay())%7+1) % 7);
Or more simple:
let now = new Date();
let day = 1; // Monday
if (day > 6 || day < 0)
day = 0;
while (now.getDay() != day) {
now.setDate(now.getDate() + 1);
}
now.setDate(now.getDate() + 1);
console.log(now); // next Monday occurrence