UNPKG

@jsbits/add-months

Version:

Adds or subtracts N months to any JavaScript Date, local or UTC.

64 lines (63 loc) 1.8 kB
/* Date.prototype addMonths and addUTCMonths v1.1.2 @license MIT */ (function (DateProto) { "use strict"; var addMonthsLoc = function (date, count) { var day = date.getDate(); date.setMonth(date.getMonth() + count, day > 28 ? 28 : day); if (day > 28) { var month = date.getMonth(); date.setDate(day); if (date.getMonth() !== month) { date.setDate(0); } } return date; }; var addMonthsUTC = function (date, count) { var day = date.getUTCDate(); date.setUTCMonth(date.getUTCMonth() + count, day > 28 ? 28 : day); if (day > 28) { var month = date.getUTCMonth(); date.setUTCDate(day); if (date.getUTCMonth() !== month) { date.setUTCDate(0); } } return date; }; var addMonths = function (startdate, count, asUTC) { var date = new Date(+startdate); count |= 0; if (!count || isNaN(date)) { return date; } return asUTC ? addMonthsUTC(date, count) : addMonthsLoc(date, count); }; var _addMonthsP = function (_this, count, asUTC) { if (_this instanceof Date) { var date = addMonths(_this, count, asUTC) return _this.setTime(+date) } throw new TypeError('Method Date.prototype.add' + (asUTC ? 'UTC' : '') + 'Months called on incompatible receiver ' + _this) } Object.defineProperties(DateProto, { addMonths: { value: function (count) { return _addMonthsP(this, count, false) }, configurable: true, writable: true, }, addUTCMonths: { value: function (count) { return _addMonthsP(this, count, true) }, configurable: true, writable: true, }, }) })(Date.prototype);