Calculate date difference using Javascript

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 :
Note : Please do not remove this reference
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “”>
<html xmlns=””>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<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);


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

One Response to Calculate date difference using Javascript

  1. e cig says:

    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

Your email address will not be published.