Posts Tagged ‘extending the DOM’

Javascript Date Object – Adding and Subtracting Months

Thursday, September 18th, 2008

There is a slight problem with the Javascript Date() Object when trying to advance to the next month or go back to the previous month. For example, if your date is set to October 31, 2008 and you add one month, you'd probably expect the new date to be November 30, 2008 because November 31st doesn't exist. This, however, isn't the case. Javascript automatically advances your Date object to December 1st. This functionality is very useful in most situations(i.e. adding days to a date, determining the number of days in a month or if it's a leap year), but not for adding/subtracting months. I've put together some functions below that extend the Date() object: nextMonth() and prevMonth() See the example below for their usage and please feel free to use these in your applications.

Extends the Date Object:

function prevMonth(){
var thisMonth = this.getMonth();
this.setMonth(thisMonth-1);
if(this.getMonth() != thisMonth-1 && (this.getMonth() != 11 || (thisMonth == 11 && this.getDate() == 1)))
this.setDate(0);
}
function nextMonth(){
var thisMonth = this.getMonth();
this.setMonth(thisMonth+1);
if(this.getMonth() != thisMonth+1 && this.getMonth() != 0)
this.setDate(0);
}

Date.prototype.nextMonth = nextMonth;
Date.prototype.prevMonth = prevMonth;

Example of Usage:


function getPrevMonth(){
var today = new Date(2008,9,31); //set "today" to October 31, 2008
today.prevMonth(); //show one month earlier -> September 30, 2008 (instead of September 31, 2008 which converts to October 1st, 2008
}
function getNextMonth(){
var today = new Date(2008,9,31); //set "today" to October 31, 2008
today.nextMonth(); //show one month later -> November 30, 2008 (instead of November 31, 2008 which converts to December 1st, 2008
}