Narcoleptic's Patch Mangler
Unleash awesomeness. Private packages, team management tools, and powerful integrations. Get started with npm Orgs »

@jsbits/add-months

1.1.2 • Public • Published

@jsbits/add-months

Part of the JSBits suite.

License npm Version minified size
AppVeyor Test Travis Test coverage code quality maintainability

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

Install

For NodeJS and JS bundlers:

npm i @jsbits/add-months
# or 
yarn add @jsbits/add-months

or load addMonths in the browser:

<script src="https://unpkg.com/@jsbits/add-months/index.b.min.js"></script>

Targets

  • ES5 compatible browser
  • NodeJS v4.2 or later

addMonths(startdate, count, [asUTC])Date

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 (DST).

This function does not change the original date.

Param Type Default Description
startdate Date | number A value parseable as a JavaScript Date
count number Number of months to add or subtract
[asUTC] boolean false If true, handle the date as UTC

Returns: Date - A new, adjusted Date instance.

Since 1.0.0
Group: date
Author/Maintainer: aMarCruz

Example

import addMonths from '@jsbits/add-months'
 
// Helper for creating a local date based on a string
const toDate = (ds) => {
  const dt = ds.split(/[-T: ]/)
  return new Date(dt[0], dt[1] - 1, dt[2], ~~dt[3], ~~dt[4], ~~dt[5])
}
 
// can increment above one year
addMonths(toDate('2017-01-08'), 15)  // ⇒ 2018-04-08 06:00:00
 
// decrement works
addMonths(toDate('2017-01-01'), -1)  // ⇒ 2016-12-01 06:00:00
 
// avoids day overflow
addMonths(toDate('2017-01-31'), 1)  // ⇒ 2017-02-28 06:00:00
 
// can handle leap years
addMonths(toDate('2016-01-31'), 1)  // ⇒ 2016-02-29 06:00:00
 
// with the third parameter, date is handled as UTC
addMonths(new Date('2015-01-01T05:00:00Z'), 1, true)  // ⇒ 2015-02-01 05:00:00Z
 
// it accepts numericals parameters
addMonths(1541898143424, 1)  // ⇒ 2018-12-11 01:02:23
 
// returns an Invalid Date (i.e. NaN) for other types,
// to avoid undesired conversions to the current date.
addMonths(false, 1)  // ⇒ NaN

Date.prototype.addMonths

If you prefer, you can inject addMonths into the Date.prototype by requiring 'proto' or by loading the IIFE from 'proto.js' in the browser:

<script src="https://unpkg.com/@jsbits/add-months/proto.js"></script>

The new functionality is exposed in separate methods, with an API similar to other methods of the Date object:

  • addMonths for local dates
  • addUTCMonths for UTC dates

Both methods receive the number of months to add or subtract and update the value of the object directly.

The returned value is the number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date, or NaN if the date is invalid. The asUTC flag is not necessary.

Using Date.prototype.addMonths.call with other type than Date generates a TypeError.

This example shows the behavior of both methods using the same date instance:

// this is using ESM syntax, but you can use require()
import '@jsbits/add-months/proto'
 
// helpers
const showLoc = (dt) => console.log('' + dt)
const showUTC = (dt) => console.log(dt.toJSON())
const showRes = (dt) => console.log(dt)
 
const date = new Date(2019, 0, 30, 20, 0, 0)
 
showLoc(date)                   // ⇒ Wed Jan 30 2019 20:00:00 GMT-0600 (CST)
showRes(date.addMonths(1))      // ⇒ 1551405600000
showLoc(date)                   // ⇒ Thu Feb 28 2019 20:00:00 GMT-0600 (CST)
 
showUTC(date)                   // ⇒ 2019-03-01T02:00:00.000Z
showRes(date.addUTCMonths(1))   // ⇒ 1554084000000
showUTC(date)                   // ⇒ 2019-04-01T02:00:00.000Z

Note about DST

For local dates, the time offset may change if the resulting date has DST activation different from the original.

For example, if a GMT-0600 zone changes to GMT-0500 between May and October, the following will shift the time offset preserving the hour:

const origin = new Date('2018-01-20T16:00:00')  // ⇒ 2018-01-20 16:00 GMT-0600
const result = addMonths(origin, 6)             // ⇒ 2018-07-20 16:00 GMT-0500

The same dates in UTC, which has no time offset, show the change:

console.log(origin.toISOString())   // ⇒ 2018-01-20T22:00:00.000Z
console.log(result.toISOString())   // ⇒ 2018-07-20T21:00:00.000Z

The same happens if you apply a setMonth(6) to that date, which is correct and generally expected, just keep it in mind if you handle UTC dates based on local dates.

Date from String

Avoid creating dates with strings, it is inconsistent.

From Date at MDN:

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

Even node 6 has problems with this. Do not use it except with the UTC ISO-8601 format.

Imports

All the JSBits functions works in strict mode and are compatible with:

  • ES5 browsers, through the jQuery $.jsbits object or the global jsbits.
  • ESM Bundlers, like webpack and Rollup.
  • ES modules for modern browsers or NodeJS with the --experimental-modules flag.
  • CommonJS modules of NodeJS, jspm, and others.
  • Babel and TypeScript, through ES Module Interop.

Please see the Distribution Formats in the JSBits README to know about all the variants.

Support my Work

I'm a full-stack developer with more than 20 year of experience and I try to share most of my work for free and help others, but this takes a significant amount of time and effort so, if you like my work, please consider...

Of course, feedback, PRs, and stars are also welcome 🙃

Thanks for your support!

License

The MIT License.

© 2018-2019 Alberto Martínez – Readme powered by jscc and jsdoc-to-markdown

install

npm i @jsbits/add-months

Downloadsweekly downloads

2

version

1.1.2

license

MIT

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar
Report a vulnerability