Click here to Skip to main content
15,938,578 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an input box where users can enter a number , positive and negative, to calculate either business or Calendar days. I am using jquery to calculate the days and it works when the number entered is a positive number, for example (10) but does not work when the number entered is negative for example (-10) . Below is my code. Any help will be appreciated

What I have tried:

function AddBusinessDays(startDate, workDaysToAdd) {
    var curDate = new Date(startDate);
    var realDaysToAdd = 0;
    while (workDaysToAdd > 0) {
        if (IsWorkDay(curDate)) {
        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 === 5) {
        isWorkDay = false;
    else {
        isWorkDay = !isNationalDay(curDate);
    return isWorkDay;

function isNationalDay(date) {
    var thisDate = new Date(date);
    var thisMoment = moment(thisDate);
    var holiday =;
    var isHoliday = holiday != 'undefined' && holiday != null && holiday.length > 0;
    return isHoliday;
Richard Deeming 16-Mar-22 4:42am    
"does not work when the number entered is negative"
Probably because you explicitly don't process negative numbers:
while (workDaysToAdd > 0)
Alex Aniapam 16-Mar-22 17:29pm    
Thanks for your response. I have finally solved it by adding the code below

1 solution

while (workDaysToAdd < 0) {
       if (IsWorkDay(curDate)) {

       curDate.setDate(curDate.getDate() - 1);
Share this answer
PIEBALDconsult 16-Mar-22 20:28pm    
Please don't try to answer your own question. If you have details to add to the question, please use the "Improve question" button.
Richard Deeming 17-Mar-22 4:59am    
This is actually an answer to the question, as prompted by my comment. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900