- SPLessons

How do i find the difference between tw...

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

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.

  1. jquery-ui.css
  2. jquery-1.10.2.js
  3. 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

<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">

        onSelect: function(selected) {
          $("#ToDate").datepicker("option","minDate", selected)
        onSelect: function(selected) {
           $("#FromDate").datepicker("option","maxDate", selected)

Step3 :

Below code is to calculate difference between two dates

<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)");
	alert("Please select dates");
	return false;


Step4 :

Add below content in ‘index.html’ in page body to select dates

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>

Open the ‘index.html’ in any browser and trying to submit your form, you will get validation on form.