Skip to content

Instantly share code, notes, and snippets.

@fenying
Last active November 25, 2018 08: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 fenying/b9b0d759a0191d90ae3ae3895fc295b1 to your computer and use it in GitHub Desktop.
Save fenying/b9b0d759a0191d90ae3ae3895fc295b1 to your computer and use it in GitHub Desktop.
Get the same day of neighboring month.
/**
* Get the same day in neighboring month, e.g.
*
* Input: ("2018-10-31", 1) Output: 2018-11-30
*
* Input: ("2018-10-30", 1) Output: 2018-11-30
*
* Input: ("2018-01-31", 1) Output: 2018-02-28
*
* Input: ("2020-01-31", 1) Output: 2020-02-29
*
* Input: ("2018-01-31", 5) Output: 2018-06-30
*
* Input: ("2018-01-31", 12) Output: 2019-01-31
*
* Input: ("2018-01-31", 13) Output: 2019-02-28
*
* @param dt The date-time expression, a timestamp, or a Date object.
* @param n The n(th) month after the `dt`.
* Positive integer stands for future month.
* Negative integer stands for passed month.
*/
export function getSameDayOfNeighboringMonth(
dt: number | Date | string,
n: number = 1
): Date {
let d = new Date(dt);
const nextDate = new Date(
d.getFullYear(),
d.getMonth() + n,
d.getDate(),
d.getHours(),
d.getMinutes(),
d.getSeconds(),
d.getMilliseconds()
);
const r = (d.getMonth() + n) % 12;
if (r < 0) { // Fixed when backward previous years
if (r + 12 === nextDate.getMonth()) {
return nextDate;
}
}
else {
if (r === nextDate.getMonth()) {
return nextDate;
}
}
return new Date(
d.getFullYear(),
d.getMonth() + n + 1,
0,
d.getHours(),
d.getMinutes(),
d.getSeconds(),
d.getMilliseconds()
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment