Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use moment.js to add days, excluding weekends?

I'm setting a default follow-up date two days from current date, which currently works:

const Notify = moment().add(2, 'days').toDate();

However, I would like to exclude weekends. So I installed moment WeekDay, but I can't seem to get it to work with adding days to the current date. The documentation calls for:

moment().weekday(0)

But I can't get that to work with adding in two days forward. Any ideas?

like image 659
Micah C Avatar asked Sep 20 '18 14:09

Micah C


2 Answers

This solution is simple, easy to follow, and works well for me:

function addBusinessDays(originalDate, numDaysToAdd) {
  const Sunday = 0;
  const Saturday = 6;
  let daysRemaining = numDaysToAdd;

  const newDate = originalDate.clone();

  while (daysRemaining > 0) {
    newDate.add(1, 'days');
    if (newDate.day() !== Sunday && newDate.day() !== Saturday) {
      daysRemaining--;
    }
  }

  return newDate;
}
like image 95
zeckdude Avatar answered Sep 23 '22 08:09

zeckdude


Try: moment-business-days

It should help you.

Example:

var momentBusinessDays = require("moment-business-days")

momentBusinessDays('20-09-2018', 'DD-MM-YYYY').businessAdd(3)._d 

Result:

Tue Sep 25 2018 00:00:00 GMT+0530 (IST)
like image 40
Harshal Y. Avatar answered Sep 24 '22 08:09

Harshal Y.