Thursday, November 21, 2019

Add business days with moment.js

Date.prototype.addBusinessDays = function (businessDays: number) {  // 5 business days in a week  const weeks = Math.floor(businessDays / 5);
  // Convert business days (5 days in a week) to regular days (7 days in a week)  const days = weeks * 7;  const date = moment(this); // Convert the incoming date value to a moment value.  const newDate = moment(this).add(days + (businessDays % 5), 'days');
  if (newDate.day() < date.day() || newDate.day() % 6 === 0) {    // Add 2 more days if we land on a weekend, or we went through a weekend.    newDate.add(2, 'days'); // .add is not pure and will change the underlying value  }
  return newDate.toDate();};