How to exclude weekends between two dates using Moment.js

Here you go!

function addWeekdays(date, days) {
  date = moment(date); // use a clone
  while (days > 0) {
    date = date.add(1, 'days');
    // decrease "days" only if it's a weekday.
    if (date.isoWeekday() !== 6 && date.isoWeekday() !== 7) {
      days -= 1;
    }
  }
  return date;
}

You call it like this

var date = addWeekdays(moment(), 5);

I used .isoWeekday instead of .weekday because it doesn’t depend on the locale (.weekday(0) can be either Monday or Sunday).

Don’t subtract weekdays, i.e addWeekdays(moment(), -3) otherwise this simple function will loop forever!

Updated JSFiddle http://jsfiddle.net/Xt2e6/39/ (using different momentjs cdn)

Leave a Comment