I am using jquery and moment js to calculate Business Days. For some strange reasons 31 December 2022 is a Saturday but my code is still showing it as working day. I have a start Date of 30th December, 2022 and 1 (one) workDaysToAdd which falls on Saturday the 31st, December 2022 which is not working Business day. My code is not skipping the saturday 31st, December 2022.
function AddBusinessDays(startDate, workDaysToAdd) {
var curDate = new Date(startDate);
var realDaysToAdd = 0;
while (workDaysToAdd > 0) {
realDaysToAdd ;
if (IsWorkDay(curDate)) {
workDaysToAdd--;
}
curDate.setDate(curDate.getDate() 1);
}
return realDaysToAdd;
}
function IsWorkDay(date) {
var curDate = new Date(date);
var dayOfWeek = curDate.getDay();
var isWorkDay;
if (dayOfWeek == 0 || dayOfWeek == 6) {
isWorkDay = false;
}
else {
isWorkDay = !isNationalDay(curDate);
}
return isWorkDay;
}
function isNationalDay(date) {
var thisDate = new Date(date);
var thisMoment = moment(thisDate);
var holiday = thisMoment.holiday();
var isHoliday = holiday != 'undefined' && holiday != null && holiday.length > 0;
return isHoliday;
}
CodePudding user response:
Your logic is incorrect. You start on a Friday and check if it's a workday (it is) and decrement workDaysToAdd
. If that started as 1
, it is now 0
and your while
loop exits.
Move your date increment to the top of the loop so you're checking the next day.
function AddBusinessDays(startDate, workDaysToAdd) {
const curDate = new Date(startDate);
let realDaysToAdd = 0;
while (workDaysToAdd > 0) {
curDate.setDate(curDate.getDate() 1); // move this to the top of the loop
realDaysToAdd ;
if (IsWorkDay(curDate)) {
workDaysToAdd--;
}
}
return realDaysToAdd;
}
function IsWorkDay(date) {
return date.getDay() % 6 && !isNationalDay(date);
}
function isNationalDay(date) {
return false; // no idea where the moment.holiday() comes from
}
const startDate = new Date(Date.UTC(2022, 11, 30));
console.log("start", startDate);
console.info(AddBusinessDays(startDate, 1))