Skip to content

Instantly share code, notes, and snippets.

@parveen14
Created December 3, 2019 14:15
Show Gist options
  • Save parveen14/36e21d01f734bc555319e73686ac6bc0 to your computer and use it in GitHub Desktop.
Save parveen14/36e21d01f734bc555319e73686ac6bc0 to your computer and use it in GitHub Desktop.
Add WorkDays ( monday to friday ) to any moment
const moment = require('moment');
moment.fn.addWorkdays = function (days) {
// Getting negative / positive increment
var increment = days / Math.abs(days);
// Looping weeks for each full 5 workdays
var date = this.clone().add(Math.floor(Math.abs(days) / 5) * 7 * increment, 'days');
// Account for starting on Saturdays and Sundays
if (date.isoWeekday() === 6) { date.add(-increment, 'days'); }
else if (date.isoWeekday() === 7) { date.add(-2 * increment, 'days'); }
// Adding / removing remaining days in a short loop, jumping over weekends
var remaining = days % 5;
while (remaining != 0) {
date.add(increment, 'days');
if (date.isoWeekday() !== 6 && date.isoWeekday() !== 7)
remaining -= increment;
}
return date;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment