I needed an easy way to add or subtract months from a JavaScript date and have it do it correctly for situations like the end of the month where the new month has different days, but also for it to roll backward/forward to a different year when necessary.
Here is a simple solution which extends the built-in Date class:
Date.prototype.addMonths = function( months )
{
var monthsTotal = this.getMonth() + this.getYear() * 12 + months;
var day = this.getDate();
var year = monthsTotal / 12;
var month = monthsTotal % 12;
var maxDays = this.getDaysInMonth( year, month );
if( day > maxDays )
{
day = maxDays;
OutputLog( "day: " + day );
}
this.setYear( year );
this.setMonth( month );
this.setDate( day );
}
Date.prototype.getDaysInMonth = function( year, month )
{
var days = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
//
// Check for leap year
if( month == 1 && year % 4 == 0 && ( year % 100 || year % 400 == 0 ) )
{
return 29;
}
return days[ month ];
}
You would use these new methods as follows:
var test = new Date( 2011, 2, 30, 06, 10, 11 ); test.addMonths( -1 ); alert( test); test = new Date( 2011, 1, 30, 06, 10, 11 ); test.addMonths( 12 ); alert( test );
And here is an additional useful method to provide a way of returning the month name:
Date.prototype.getMonthName = function()
{
var names = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
return names[ this.getMonth() ];
}



