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)
Those iteration looped solutions would not fit my needs.They were too slow for large numbers.So I made my own version:
https://github.com/leonardosantos/momentjs-business
Hope you find it useful.
https://github.com/andruhon/moment-weekday-calc plugin for momentJS might be helpful for similar tasks
It does not solves the exact problem, but it is able to calculate specific weekdays in the range.
Usage:
moment().isoWeekdayCalc({ rangeStart: '1 Apr 2015', rangeEnd: '31 Mar 2016', weekdays: [1,2,3,4,5], //weekdays Mon to Fri exclusions: ['6 Apr 2015','7 Apr 2015'] //public holidays}) //returns 260 (260 workdays excluding two public holidays)