JavaScript Date Add Function

Posted on: October 28th, 2013 by admin No Comments

I think doing anything with dates is horrible in JavaScript compared to PHP but here is a function to make adding x days to a date a little easier:

function dateAdd(theDate, numDays) {
 
	/** 
	 * Date must be YYYY-MM-DD or DD-MM-YYYY - other formats will not work
	 */
 
	numDays = parseInt(numDays);
 
	if(theDate.indexOf("/") !== -1) var seperator = '/';
	else if(theDate.indexOf("-") !== -1) var seperator = '-';
	else return false;
 
	var parts = theDate.split(seperator);
 
	var month = parts[1];
	if(parts[2].length==4) {
		var day = parts[0];
		var year = parts[2];
	} else if(parts[0].length==4) {
		var day = parts[2];
		var year = parts[0];
	}
 
	var date = new Date(year, month-1, day);
 
	var newdate = new Date(date);
 
	newdate.setDate(newdate.getDate() + numDays);
 
	var dd = newdate.getDate();
	var mm = newdate.getMonth() + 1;
	var y = newdate.getFullYear();
	return dd + '/'+ mm + '/'+ y;
 
}