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?
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?
Months have a 0-based index, it should alert(4) which is 5 (may);
Just to add on to the accepted answer and the comments.
Simple solution:
2678400000
is 31 day in millisecondsUpdate:
Use this data to build our own function:
2678400000
- 31 day2592000000
- 30 days2505600000
- 29 days2419200000
- 28 daysI wrote this alternative solution which works fine to me. It is useful when you wish calculate the end of a contract. For example, start=2016-01-15, months=6, end=2016-7-14 (i.e. last day - 1):
Examples:
As demonstrated by many of the complicated, ugly answers presented, Dates and Times can be a nightmare for programmers using any language. My approach is to convert dates and 'delta t' values into Epoch Time (in ms), perform any arithmetic, then convert back to "human time."
This was written for a slightly different use case, but you should be able to easily adapt it for related tasks.
EDIT: Full source here!