I’ve found this code online to return the next working day and exclude weekends.
function nextWorkDay() {
const date = new Date();
do {
date.setDate(date.getDate() + 1);
} while (!(date.getDay() % 6));
return date;
}
However, the % 6 part in my understanding excludes Saturdays and Sundays.
How can I modify it to only exclude Saturdays?
>Solution :
getDay returns a value between 0 and 6, inclusive. 0 is Sunday.
So, date.getDay() % 6 will result in 0 if getDay returns either 0 or 6.
Don’t use modulo – use === to exclude exactly one day, not both zero and another day.
} while (date.getDay() === 6);
You also don’t need a loop anymore – a single condition will be clearer.
function nextWorkDay() {
const date = new Date();
date.setDate(date.getDate() + 1);
if (date.getDay() === 6) date.setDate(date.getDate() + 1);
return date;
}