Home Tutorial Javascript Javascript calculate number of days between two dates

 
 

Share on Google+Share on Google+
Javascript calculate number of days between two dates
Posted on: December 8, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to calculate number of days between two dates.

Javascript calculate number of days between two dates

In this tutorial, you will learn how to calculate number of days between two dates.For this, you need to use the Date object  to retrieve the Date's millisecond value using Date.getTime() function. Once both Dates have been converted, subtracting the later one from the earlier one returns the difference in milliseconds. The desired interval can then be determined by dividing that number by the corresponding number of milliseconds.

Example:

<html>
<head>
<script type="text/javascript">
function findDiff(){
var dob1= document.getElementById("dob1").value;
var dob2= document.getElementById("dob2").value;
var date1 = new Date(dob1);
var date2=new Date(dob2);

var ONE_DAY = 1000 * 60 * 60 * 24
var d1 = date1.getTime()
var d2 = date2.getTime()
var diff = Math.abs(d1 - d2)
document.getElementById("days").value=Math.round(diff/ONE_DAY);
}
</script>
</head>
<body>
<pre>
Enter Date1(yyyy-mm-dd): <input type="text" name="dob1" id="dob1" />
Enter Date2(yyyy-mm-dd): <input type="text" name="dob2" id="dob2" />
Number of days: <input type="text" name="days" id="days" />
<input type="submit" value="calculate" onclick="findDiff();">
</pre>
</body>
</html>

Advertisement

Related Tags for Javascript calculate number of days between two dates:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 8, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com