UNPKG

@jsbits/add-months

Version:

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

75 lines (72 loc) 2.4 kB
/* @jsbits/add-months @author aMarCruz @version 1.1.2 ESM+ES6 @license MIT */ /* eslint-disable */ const addMonthsLoc = (date, count) => { const day = date.getDate(); date.setMonth(date.getMonth() + count, day > 28 ? 28 : day); if (day > 28) { const month = date.getMonth(); date.setDate(day); if (date.getMonth() !== month) { date.setDate(0); } } return date; }; const addMonthsUTC = (date, count) => { const day = date.getUTCDate(); date.setUTCMonth(date.getUTCMonth() + count, day > 28 ? 28 : day); if (day > 28) { const month = date.getUTCMonth(); date.setUTCDate(day); if (date.getUTCMonth() !== month) { date.setUTCDate(0); } } return date; }; const _toString = Object.prototype.toString; const toDate = (src) => { const type = _toString.call(src); return new Date(type === '[object Date]' || type === '[object Number]' ? +src : NaN); }; /** * Returns a date occurring `count` months after `startdate` or, if `count` is * negative, the date occurring `count` months before `startdate`. * * - If `startdate` is not a Date or number that can be converted to a * valid date, returns a new Date instance with an invalid date. * * - If `count` is evaluated as zero, returns a new Date instance with the * the same value as `startdate`. * * - If there is an overflow in the day, the date is adjusted to the last * valid day of the expected month. * * The third parameter is optional and indicates if the date is UTC. It is * necessary to differentiate UTC dates from locals and avoid errors due to the * [Daylight Saving Time](https://en.wikipedia.org/wiki/Daylight_saving_time) * (DST). * * This function does not change the original date. * * @param {Date|number} startdate A value parseable as a JavaScript Date * @param {number} count Number of months to add or subtract * @param {boolean} [asUTC=false] If `true`, handle the date as UTC * @returns {Date} A new, adjusted Date instance. * @since 1.0.0 */ const addMonths = function _addMonths(startdate, count, asUTC) { const date = toDate(startdate); count |= 0; if (!count || isNaN(date)) { return date; } return asUTC ? addMonthsUTC(date, count) : addMonthsLoc(date, count); }; export default addMonths; //# sourceMappingURL=index.mjs.map