We can kind of achieve this using the standard date libraries but it doesn’t work for edge cases.
For example, say we want to add one month to January 31st 2009. We would expect one month from this date to be February 28th 2009:
var jan312009 = new Date(2009, 1-1, 31); var oneMonthFromJan312009 = new Date(new Date(jan312009).setMonth(jan312009.getMonth()+1));
The output of these two variables is:
Sat Jan 31 2009 00:00:00 GMT+1100 (EST) Tue Mar 03 2009 00:00:00 GMT+1100 (EST)
Not quite what we want!
Luckily there is a library called datejs which has taken care of this problem for us. It provides a really nice DSL which makes it very easy for us to do what we want.
We can add a month to a date very easily now:
var jan312009 = new Date(2009, 1-1, 31); var oneMonthFromJan312009 = new Date(jan312009).add(1).month();
Sat Jan 31 2009 00:00:00 GMT+1100 (EST) Sat Feb 28 2009 00:00:00 GMT+1100 (EST)