Saturday, December 11, 2010

javascript Date difference in days

Many times it is required to compare two Date object and get the difference between the dates in days. Following javascript function will get you the difference in days

Date.getDaysDifference = function(fromDate,toDate)
{
   fromDate = new Date(fromDate.getFullYear(),fromDate.getMonth(),fromDate.getDate());
   toDate = new Date(toDate.getFullYear(),toDate.getMonth(),toDate.getDate());
   return ((toDate-fromDate)/86400000); //Total millisends in day =1000*60*60*24
}

Date.prototype.getDaysDifference = function(toDate)
{
   return Date.getDaysDifference(this,toDate);
}


Usage Example

var fromDate= new Date(2010,1,1);
var toDate= new Date(); //today's date
alert(Date.getDaysDifference(fromDate,toDate));
//or
alert(fromDate.getDaysDifference(toDate));

No comments:

Post a Comment