Created
May 13, 2021 21:39
-
-
Save joepuzzo/cee460469d7140b9f7d5eb4558d404e8 to your computer and use it in GitHub Desktop.
Adds a month
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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