Categories
JavaScript Answers

How to calculate number of working days between two dates in JavaScript using moment.js?

Spread the love

Sometimes, we want to calculate number of working days between two dates in JavaScript using moment.js.

In this article, we’ll look at how to calculate number of working days between two dates in JavaScript using moment.js.

How to calculate number of working days between two dates in JavaScript using moment.js?

To calculate number of working days between two dates in JavaScript using moment.js, we can use a while loop.

For instance, we write:

const calcBusinessDays = (startDate, endDate) => {
  const day = moment(startDate);
  let businessDays = 0;
  while (day.isSameOrBefore(endDate, 'day')) {
    if (day.day() !== 0 && day.day() !== 6) {
      businessDays++;
    }
    day.add(1, 'd');
  }
  return businessDays;
}

const startDate = '2022-01-01'
const endDate = '2022-01-31'
console.log(calcBusinessDays(startDate, endDate))

to define the calcBusinessDays function that takes the startDate and endDate strings.

In it, we set day to the startDate parsed into a moment object with moment.

Then we use a while loop that calls day.isSameOrBefore with endDate to run the loop until day is the same as endDate.

In the loop, we check if the week day isn’t 0 or 6, which are Saturday and Sunday respectively.

If the condition is true, then we add 1 to businessDays.

And then we add 1 day to day with day.add(1, 'd').

Finally, we return businessDays.

As a result, 21 is logged in the console.

Conclusion

To calculate number of working days between two dates in JavaScript using moment.js, we can use a while loop.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *