moment.js Tips n Tricks: Add Business Days

I needed a really quick and dirty way to add business days to a date.  We are currently using moment.js to handle our date functionality.  Here is the script I used:

    public addBusinessDays(date, daysToAdd) {
        var cnt = 0;
        var tmpDate = moment(date);
        while (cnt < daysToAdd) {
            tmpDate = tmpDate.add('days', 1);
            if (tmpDate.weekday() != moment().day("Sunday").weekday() && tmpDate.weekday() != moment().day("Saturday").weekday()) {
                cnt = cnt + 1;
            }
        }

        return tmpDate;
    }

Updated:

Here is another way to handle the same thing that works better for large numbers. Full credit for this code goes to leonardosantos, I am reposting it so that I have a copy.
https://github.com/leonardosantos/momentjs-business/blob/master/momentjs-business.js

/**
 * momentjs-business.js
 * businessDiff (mStartDate)
 * businessAdd (numberOfDays)
 */
(function () {
  var moment;
  moment = (typeof require !== "undefined" && require !== null) &&
           !require.amd ? require("moment") : this.moment;

  moment.fn.businessDiff = function (start) {
    start = moment(start);
    var end = this.clone();
    var start_offset = start.day() - 7;
    var end_offset = end.day();

    var end_sunday = end.clone().subtract('d', end_offset);
    var start_sunday = start.clone().subtract('d', start_offset);
    var weeks = end_sunday.diff(start_sunday, 'days') / 7;

    start_offset = Math.abs(start_offset);
    if(start_offset == 7)
      start_offset = 5;
    else if(start_offset == 1)
      start_offset = 0;
    else
      start_offset -= 2;


    if(end_offset == 6)
      end_offset--;

    return weeks * 5 + start_offset + end_offset;
  };

  moment.fn.businessAdd = function (days) {
    var d = this.clone().add('d', Math.floor(days / 5) * 7);
    var remaining = days % 5;
    while(remaining){
      d.add('d', 1);
      if(d.day() !== 0 && d.day() !== 6)
        remaining--;
    }
    return d;
  };

}).call(this);

3 thoughts on “moment.js Tips n Tricks: Add Business Days

    • Hi, I’m sure there is a much cleaner way to refactor this code. Many changes have been made to Moment.js since I first wrote this. 🙂

      Like

Leave a comment