Sunday, January 30, 2011

Date Add in Javascript (Tips & Trick)

Hi Guys, Good day to you ! allow me repost a programming tips that I copied from my another blog. enjoy !


I came across from a problem where I found a little difficulty using the existing Javascript standard date functions. especially when I need to 'add' the date forward or backward. let say, for example, I want to know what is the date one month after 'now', or what is the date 7 days from now ?

I'm so familiar with Coldfusion where it provide dateAdd() function where you can use to add a date with a certain unit of time. Unfortunately, there's none as easy as this in Javascript.

Therefore I created my own Javascript functions that works similar with it. here is the code.

 //Simple Date Add Function
function dateAdd(datepart,number,objDate){
y = objDate.getFullYear();
m = objDate.getMonth()+1;
d = objDate.getDate();
hr = objDate.getHours();
mn = objDate.getMinutes();
sc = objDate.getSeconds();
newY=y;
newM=m;
newD=d;
if (datepart== 'y'){
newY = parseInt(y) + parseInt(number);
} else if (datepart== 'm') {
newM = parseInt(m) + parseInt(number);
} else {
newD = parseInt(d) + parseInt(number);
}
objNewDate = new Date(newY,newM,newD,hr,mn,sc);
return objNewDate;
}


This function took 3 parameters,

- Datepart. the option is "y" for year, "m" for month and "d" for day. currently this is the only options provided ^^, sure you can expand the usability on your own if you would so.


- Number. Number of units of datepart to add to date (positive, to get dates in the future; negative, to get dates in the past). Number must be an integer.


- objDate. Javascript Date/time object



Example :



function dateAddSample() {
example1 = dateAdd("m",3,new Date()); //add current date 3 months forward
example2 = dateAdd("m",-6,new Date()); //add current date 6 months backward
example3 = dateAdd("d",7,new Date()); //add current date 7 days forward
alert(example1);
alert(example2);
alert(example3);
}

That's all the code, hope it helpful. cheers !

No comments: