I’m looking for the easiest, cleanest way to add X months to a JavaScript date.
I’d rather not handle the rolling over of the year or have to write my own function.
Is there something built in that can do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The following function adds months to a date in JavaScript (source). It takes into account year roll-overs and varying month lengths:
The above solution covers the edge case of moving from a month with a greater number of days than the destination month. eg.
If the day of the month changes when applying
setMonth, then we know we have overflowed into the following month due to a difference in month length. In this case, we usesetDate(0)to move back to the last day of the previous month.Note: this version of this answer replaces an earlier version (below) that did not gracefully handle different month lengths.