moment.js Business Day Calculations
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script>
<div class="demo">
<label for="StartDate">
Click to select date
</label>
<input type="text" id="StartDate" readonly />
<div id="Results" />
</div>
CSS
html, body {
font-family: Arial;
font-size: 9pt;
line-height: 2em;
}
div.demo {
padding:10px;
margin:10px;
border:1px solid #ddd;
}
JavaScript
/**
* moment.js plugin: additional methods
* businessDiff
* businessAdd
* businessSubtract
*/
(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;
}
}).call(this);
/**
* Demo
*/
$(document).ready(function () {
var $StartDate = $('#StartDate'),
$Results = $('#Results');
function StartDate_OnChange (text, inst) {
var dStartDate = $StartDate.datepicker('getDate'),
mStartDate = moment(dStartDate),
iDays = 3,
mXDays = mStartDate.clone().add('days', iDays),
mBDays = mStartDate.clone().businessAdd(iDays),
szFormat = 'ddd, D MMM YYYY',
szXDays = mXDays.format(szFormat),
szBDays = mBDays.format(szFormat);
$Results.html(
[iDays, ' days: ', szXDays, '<br>',
iDays, ' business days: ', szBDays].join('')
);
}
$StartDate
.datepicker({
dateFormat: 'D, d M yy',
defaultDate: 0,
...