How to find the day difference between two dates (excluding weekend days) with JavaScript?

Sometimes, we want to find the day difference between two dates (excluding weekend days) with JavaScript.

In this article, we’ll look at how to find the day difference between two dates (excluding weekend days) with JavaScript.

How to find the day difference between two dates (excluding weekend days) with JavaScript?

To find the day difference between two dates (excluding weekend days) with JavaScript, we can use a while loop.

For instance, we write:

const getBusinessDatesCount = (startDate, endDate) => {
  let count = 0;
  let curDate = +startDate;
  while (curDate <= +endDate) {
    const dayOfWeek = new Date(curDate).getDay();
    const isWeekend = (dayOfWeek === 6) || (dayOfWeek === 0);
    if (!isWeekend) {
      count++;
    }
    curDate = curDate + 24 * 60 * 60 * 1000
  }
  return count;
}

const d1 = new Date(2022, 1, 1)
const d2 = new Date(2022, 1, 26)
const diff = getBusinessDatesCount(d1, d2)
console.log(diff)

to define the getBusinessDatesCount function which takes the startDate and endDate date objects.

In it, we use a while loop that loops as long as curDate is less than or equal to endDate.

We create dayOfWeek by converting the curDate timestamp to a Date instance and call its getDay method.

Then we check if dayOfWeek is 0 or 6, which is Sunday or Saturday.

And if isWeekend is false, we increment count by 1.

And then we increment curDate by 1 day by adding 24 * 60 * 60 * 1000 milliseconds.

Finally, we return the count and call getBusinessDatesCount with d1 and d2.

Therefore, diff is 19.

Conclusion

To find the day difference between two dates (excluding weekend days) with JavaScript, we can use a while loop.