Javascript code to calculate difference between two dates (Days)

The following steps will tell you how to calculate the difference of two dates which is in dd/mm/yyyy format.

Before going to the steps, let us  know little bit about Java Script Date Object. JavaScript Date Object is used to work with date and times in Java Script. It has various properties, constructors, and methods like getDay(), getMonth(), getYear(), getHours(), getMinutes() ,getTime() etc… . Following are the constructors of Date class

1. Date() -Creates Date object using the current date and time

2.Date(dateString) – Create the the date object using the given string. String format is “month day, year hours:minutes:seconds”.

3. Date(year, month, day) – Create an instance of date with the specified values (year , month, day)

4. Date(year, month, day, hours, minutes, seconds) – Create an instance of date with the specified values.

Steps :

1) The following DateDiff function accepts two date strings (dd/mm/yyyy).

2) The string is seperated by ‘/’ and stored in a array (day , month , year)

3) Now using the day, month , year, Date object is created.

4) getTime() returns the time in milliseconds. This time is divided by (1000*60*60*24) to get the Days.


function DateDiff(date1,date2)
{
var DMY =date1.split('/'); //splits the date string by '/' and stores in a array.
var DMY1 =date2.split('/');

var day= DMY[0];
var month=DMY[1];
var year=DMY[2];

var day1= DMY1[0];
var month1=DMY1[1];
var year1=DMY1[2];

var dateTemp1=new Date(year, (parseInt(month)-1),day);
var dateTemp2=new Date(year1, (parseInt(month1)-1),day1);

var Days= Math.ceil(((dateTemp2.getTime()-dateTemp1.getTime())/(1000*60*60*24)));
return Days;
}

function submitForm(){

var n =DateDiffNew('01/01/2011', '14/06/2011'); //DateDiffNew is called here
alert (n); // returns the no of days between two days.

n1 =DateDiffNew('24/03/2007', '25/03/2007');
alert (n1);

}

You may also like

Leave a Reply