Skip to content

Instantly share code, notes, and snippets.

@joepuzzo
Created May 13, 2021 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joepuzzo/cee460469d7140b9f7d5eb4558d404e8 to your computer and use it in GitHub Desktop.
Save joepuzzo/cee460469d7140b9f7d5eb4558d404e8 to your computer and use it in GitHub Desktop.
Adds a month
// Based on: https://stackoverflow.com/questions/5645058/how-to-add-months-to-a-date-in-javascript
const isLeapYear = ( year ) => {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
};
const getDaysInMonth = (d) => {
const year = d.getFullYear();
const month = d.getMonth();
return [31, (isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};
const addMonths = (d, value) => {
var n = d.getDate();
d.setDate(1);
d.setMonth(d.getMonth() + value);
d.setDate(Math.min(n, getDaysInMonth(d)));
return d;
};
const test = new Date(2021, 0, 31);
console.log(addMonths(test, 1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment