How do i find the difference between two dates using jquery
How do i find the difference between two dates using jquery
Description :
If you want know How do i find the difference between two dates using jquery, just follow the below steps to get the result.
Step1 :
Add the below scripts and styles in your project.
- jquery-ui.css
- jquery-1.10.2.js
- jquery-ui.min.js
Step2 :
Create a file named 'index.html' and add below content in that page.
To get datepicker on text boxes add below code in 'index.html' page
[javascript]
<link type="text/css" rel="stylesheet" href="css/jquery-ui.css" >
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
$("#FromDate").datepicker({
onSelect: function(selected) {
$("#ToDate").datepicker("option","minDate", selected)
}
});
$("#ToDate").datepicker({
onSelect: function(selected) {
$("#FromDate").datepicker("option","maxDate", selected)
}
});
});
</script>
[/javascript]
Step3 :
Below code is to calculate difference between two dates
[javascript]
<script language="JavaScript" type="text/javascript">
// To calulate difference b/w two dates
function CalculateDiff() {
if($("#FromDate").val()!="" && $("#ToDate").val()!=""){
var From_date = new Date($("#FromDate").val());
var To_date = new Date($("#ToDate").val());
var diff_date = To_date - From_date;
var years = Math.floor(diff_date/31536000000);
var months = Math.floor((diff_date % 31536000000)/2628000000);
var days = Math.floor(((diff_date % 31536000000) % 2628000000)/86400000);
$("#Result").html(years+" year(s) "+months+" month(s) "+days+" and day(s)");
//alert( years+" year(s) "+months+" month(s) "+days+" and day(s)");
}
else{
alert("Please select dates");
return false;
}
}
</script>
[/javascript]
Step4 :
Add below content in 'index.html' in page body to select dates
[html]
Start Date <input type="text" id="FromDate" readonly> End Date <input type="text" id="ToDate" readonly>
<br />
<div style="margin:1%;" id="Result"> </div>
<button type="button" onClick="CalculateDiff();" style="padding:1px; color:#0C6;margin-left:15%;margin-top:5%" >Calculate </button>
[/html]
Open the 'index.html' in any browser and trying to submit your form, you will get validation on form.