Monday, 18 July 2011

DateAdd JavaScript function

The following JavaScript function can be used to add the given "duration" to the given "datepart" i.e. "day", "month" or "year". See the example calls and return values and the actual function definition below.


document.write(DateAdd('1/1/2011', 10, 'day')); //returns 11/01/2011
document.write(DateAdd('1/1/2011', 10, 'month')); //returns 31/10/2011
document.write(DateAdd('1/1/2011', 10, 'year')); //returns 31/12/2020
document.write(DateAdd('1/3/2011', 1, 'year')); //returns 29/02/2012

function DateAdd(startDate, duration, datepart)
{
var day = startDate.split("/")[0];
var month = startDate.split("/")[1];
var year = startDate.split("/")[2];

if (typeof (datepart) != "undefined")
{
switch(datepart.toLowerCase())
{
case "year":
year = Number(year) + duration; day = Number(day) - 1;
break;
case "month":
month = Number(month) + duration; day = Number(day) - 1;
break;
case "day":
day = Number(day) + duration;
break;
}
}

var endDate = new Date(year, month - 1, day);
//Month starts from 0. 0 is Jan, 11 is Dec


/*new Date(2012, 0, 0) -- returns 31/Dec/2011
new Date(2012, 1, 0) -- returns 31/Jan/2012
new Date(2012, 1, -1) -- returns 30/Jan/2012
new Date(2012, 13, 1) -- returns 1/Feb/2013
*/


day = endDate.getDate();
month = endDate.getMonth() + 1;
year = endDate.getFullYear();

day = ((day + "").length == 1) ?
("0" + (day + "")) : (day + "");
month = ((month + "").length == 1) ?
("0" + (month + "")) : (month + "");

return ( day + "/" + month + "/" + year );
}



You might be also interested in DateDiff() function which can be used to find the difference in days between 2 given dates.

No comments:

Post a Comment