Skip to content

Instantly share code, notes, and snippets.

@coolaj86
Created December 8, 2022 18:16
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 coolaj86/3bfc99f865d706bbf8af17a61da3e516 to your computer and use it in GitHub Desktop.
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.
/**
* 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