Calculating date difference in JavaScript is very easy as in .Net, Java or PHP, but requires a bit different approach.

For this post i wrote simple example which can calculate difference between two dates in: days and months.

you can see running example from Here




Code is as below :

<!–
Created By : Javadotnet.in
Note : Please do not remove this reference
–>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>datedifference</title>
<script type=”text/javascript”>
function calldiff()
{
var txtdate1 = document.getElementById(‘fromdt’).value;
var txtdate2 = document.getElementById(‘todt’).value;
// split by in Indian date format. it is ddmmyyyy
var date1=new Date(txtdate1.split(‘/’)[2],txtdate1.split(‘/’)[1]-1,txtdate1.split(‘/’)[0]);
var date2=new Date(txtdate2.split(‘/’)[2],txtdate2.split(‘/’)[1]-1,txtdate2.split(‘/’)[0]);
// you can take date1 or date2 as today to check difference from today
//alert(“date :” +date1);
//alert(“date :” +date2);

var timediffsec = date1.getTime() – date2.getTime();
alert(“diff :” +timediffsec);
var timediffday = parseInt(timediffsec/(24*3600*1000));
alert(“diff in days :” +timediffday);
var timediffmonth = parseInt(timediffsec/(24*3600*1000*30));
alert(“diff in months :” +timediffmonth);

}
</script>
</head>

<body>
<table width=”100%”>
<tr>
<td width=”10%”>From date : &nbsp;</td>
<td>
<input type=”text” id=”fromdt” /></td>
</tr>
<tr>
<td width=”10%”>To Date : &nbsp;</td>
<td>
<input type=”text” id=”todt” />
</td>
</tr>
<tr>
<td colspan=”2″>
<input type=”button” onclick=”calldiff()” value=”Calculate” />
</td>
</tr>
</table>
</body>
</html>

One thought on “Calculate date difference using Javascript”
  1. Greetings! Very useful advice in this particular article!
    It’s the little changes that make the biggest changes.

    Many thanks for sharing!

Leave a Reply