Created
December 8, 2022 18:16
-
-
Save coolaj86/3bfc99f865d706bbf8af17a61da3e516 to your computer and use it in GitHub Desktop.
Add `n` month to the current date, using the last day of the target month rather than rolling over to following month.
This file contains 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
/** | |
* Add `n` months to the current date. | |
* If the target month as fewer days than the source month | |
* (i.e. 28 or 29 vs 30, or 30 vs 31) then go to the last | |
* day of the month. | |
*/ | |
function addMonth(d, n) { | |
let d1 = d.getUTCDate(); | |
let m1 = d.getUTCMonth(); | |
d.setUTCMonth(m1 + n); | |
let m2 = d.getUTCMonth(); | |
if (m1 + n !== m2) { | |
// Go to the last day of the previous month | |
d.setUTCDate(0); | |
} | |
} | |
var d = new Date('2022-01-30T23:00:00Z'); | |
addMonth(d, 1); | |
// 2022-02-28T23:00:00Z | |
var d = new Date('2022-01-30T23:00:00Z'); | |
addMonth(d, 2); | |
// 2022-03-30T23:00:00Z | |
addMonth(d, 11); | |
// 2023-01-28T23:00:00Z |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment