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?
CodePudding user response:
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;
}
CodePudding user response:
I would say always go to next day, and if it's Saturday jump to the next day. The sample working code is attached below.
const days = ["SUN", "MON", "TUS", "WED", "THU", "FRI", "SAT"]
function getNextWorkingDate() {
let now = new Date();
let today = new Date(now.setDate(now.getDate() 1)) // find next day
// Sunday = 0, Monday = 1, ... (See below):
if(today.getDay() == 7) { // if staturday, jump one more day
today = today.setDate(today.getDate() 1)
}
return today;
}
const nextWorkigDay = getNextWorkingDate();
console.log(nextWorkigDay);
console.log(days[nextWorkigDay.getDay()]);