UNPKG

moment-biz

Version:

Handle business days & weekends over multiple years

88 lines (67 loc) 2.71 kB
'use strict'; const moment = require('moment'); const utils = module.exports; function any(array, cb) { var res = false; for (let i = 0; !res && i < array.length; ++i) res = cb(array[i], i, array); return res; } // Return the holidays for the provided year (default to current year) and locale (default to global locale) moment.getHolidays = function(year = moment().year(), locale = moment.locale()) { const localeData = moment().locale(locale).localeData(); const format = localeData._config.holidayFormat || 'DD-MM'; return (localeData._config.holidays || []).map(date => (date instanceof Function ? date(year) : moment(date, format).year(year)).locale(locale) ); }; // Return the holidays of the current year on the current date moment.fn.getHolidaysOfCurrentYear = function() { return moment.getHolidays(this.year(), this.locale()); }; // Returns true if this is a weekend moment.fn.isWeekend = function() { const weekends = this.localeData()._config.weekends || [0, 6]; return weekends.indexOf(this.day()) >= 0; }; // Returns true if this is a holiday moment.fn.isHoliday = function() { return any(this.getHolidaysOfCurrentYear(), date => date.dayOfYear() === this.dayOfYear()); }; moment.fn.isFreeDay = function() { return this.isWeekend() || this.isHoliday(); }; moment.fn.isBusinessDay = function() { return !this.isFreeDay(); }; // Takes a date in format "DD-MM" and returns function that: // Takes a year and construct a complete date (DD-MM-YYYY) using the defined date and return prev Friday if it is a // Saturday and next Monday if it is a Sunday utils.adjustIfWELikeInUSA = function(date) { date = moment(date, 'DD-MM'); return year => date.year(year).day() % 6 ? moment(date) : moment(date).add(date.day() === 0 ? 1 : -1, 'day'); }; // Returns a function that takes a year and return you the // [xx] (1-N) [day] (0 = sunday - 6 = saturday) of week in [month] (1 = january - 12 = december) utils.xxDayOfMonth = function(xx, day, month) { const date = moment().startOf('day').date(1).month(month - 1); return year => { const res = moment(date).year(year); const old = moment(res); res.day(day); res.add((xx + (res < old) - 1) * 7, 'day'); return res; }; }; // Returns a function that takes a year and return you the // last [day] (0 = sunday - 6 = saturday) of [month] (1 = january - 12 = december) utils.lastDayOfMonth = function(day, month) { const date = moment().startOf('day').month(month - 1); return year => { const res = moment(date).year(year); res.endOf('month').startOf('day').day(day); if (res.month() !== month - 1) res.subtract(7, 'days'); return res; }; };