JQuery Calculate Day Difference in 2 date textboxes
I have 2 asp.net texboxes with calendar extender. I want to find out the number of days between both dates when one of the date control is changed. how can I achieve this using jquery or javascript?
This should do the trick
var start = $('#start_date').val();
var end = $('#end_date').val();
// end - start returns difference in milliseconds
var diff = new Date(end - start);
// get days
var days = diff/1000/60/60/24;
Example
var start = new Date("2010-04-01"),
end = new Date(),
diff = new Date(end - start),
days = diff/1000/60/60/24;
days; //=> 8.525845775462964
1) Html
<input type="text" id="firstDate" name="firstDate"/>
<input type="text" id="secondDate" name="secondDate"/>
2) Jquery
$("#firstDate").datepicker({
});
$("#secondDate").datepicker({
onSelect: function () {
myfunc();
}
});
function myfunc(){
var start= $("#firstDate").datepicker("getDate");
var end= $("#secondDate").datepicker("getDate");
days = (end- start) / (1000 * 60 * 60 * 24);
alert(Math.round(days));
}
Jsfiddle working example here
Hi, This is my example of calculating the difference between two dates
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery.min.js"></script>
<title>JS Bin</title>
</head>
<body>
<br>
<input class='fromdate' type="date" />
<input class='todate' type="date" />
<div class='calculated' /><br>
<div class='minim' />
<input class='todate' type="submit" onclick='showDays()' />
</body>
</html>
This is the function that calculates the difference :
function showDays(){
var start = $('.fromdate').val();
var end = $('.todate').val();
var startDay = new Date(start);
var endDay = new Date(end);
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = endDay.getTime() - startDay.getTime();
var days = millisBetween / millisecondsPerDay;
// Round down.
alert( Math.floor(days));
}
I hope I have helped you