Skip to content

Instantly share code, notes, and snippets.

@terryyounghk
Last active December 31, 2015 15:29
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terryyounghk/8006899 to your computer and use it in GitHub Desktop.
Save terryyounghk/8006899 to your computer and use it in GitHub Desktop.
Extensions for momentjs This is a small extension to moment.js, and adds the ability to add/subtract number of business days, snap to nearest business day, and calculate difference in terms of business days. Note that this simply excludes Sundays and Saturdays.
/* jshint laxbreak: true */
/**
* moment.js plugin: additional methods
* businessDiff (mStartDate)
* businessAdd (numberOfDays)
* businessSubtract (numberOfDays)
* business ([false])
*/
(function () {
var moment;
moment = (typeof require !== "undefined" && require !== null)
&& !require.amd
? require("moment")
: this.moment;
moment.fn.businessDiff = function (start) {
var a, b, c,
iDiff = 0,
unit = 'day',
iDiffDays = this.diff(start, unit);
if (this.isSame(start)) return iDiff;
if (this.isBefore(start)) {
a = start.clone();
b = this.clone();
c = -1;
} else {
a = this.clone();
b = start.clone();
c = 1;
}
do {
var iDay = b.day();
if (iDay > 0 && iDay < 6) {
iDiff++;
}
b.add(unit, 1);
} while (a.diff(b, unit) > 0);
return iDiff * c;
};
moment.fn.businessAdd = function (days) {
var i = 0;
while (i < days) {
this.add('day', 1);
if (this.day() > 0 && this.day() < 6) {
i++;
}
}
return this;
};
moment.fn.businessSubtract = function (days) {
var i = 0;
while (i < days) {
this.subtract('day', 1);
if (this.day() > 0 && this.day() < 6) {
i++;
}
}
return this;
};
moment.fn.business = function (backwards) {
while (this.day() === 0 || this.day() == 6) {
this[!!backwards ? 'businessSubtract' : 'businessAdd'](1);
}
return this;
};
}).call(this);
@leonardosantos
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment