This question already has an answer here:
I want to add months to a date in JavaScript.
For example: I am inserting date 06/01/2011
(format mm/dd/yyyy
) and now I want to add 8 months to this date. I want the result to be 02/01/2012
.
So when adding months, the year may also increase.
Split your date into year, month, and day components then use Date:
Date will take care of fixing the year.
From here:
I would highly recommend taking a look at datejs. With it's api, it becomes drop dead simple to add a month (and lots of other date functionality):
What's nice about
datejs
is that it handles edge cases, because technically you can do this using the nativeDate
object and it's attached methods. But you end up pulling your hair out over edge cases, whichdatejs
has taken care of for you.Plus it's open source!
I took a look at the datejs and stripped out the code necessary to add months to a date handling edge cases (leap year, shorter months, etc):
This will add "addMonths()" function to any javascript date object that should handle edge cases. Thanks to Coolite Inc!
Use:
->> newDate.addMonths -> mydate.addMonths
result1 = "Feb 29 2012"
result2 = "Feb 28 2011"