How to calculate difference between two dates in javascript/jquery


Simple steps to calculate difference between two date fields using JavaScript/JQuery 
In some scenario, we need to calculate the difference between two dates from the client side. Here we are going to demonstrate all about date fields using javascript such as Javascript date field validation for different format, difference between two dates in days, hours, minutes, seconds, years and weeks
Very strong and simple Javascript validation for date fields for format dd/mm/yyyy 
Following javascript function simply verify and return result for checking valid date from client side itself. It will automatically validate leap year entries and return correct result. That means if we pass ’29/02/2011′ to the function it will be return false. If we are passing ’29/02/2012′ to the function it will return true. So we don’t need to bother about the leap year or other complex things.
function isValidDate(dateStr) {
// Date validation Function
// Checks For the following valid Date formats:
// DD/MM/YYYY
var re = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\
d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))
|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]
\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/;
var valid = re.test(dateStr);
if (valid == false) {
alert(dateStr + ' Date is not in a valid format.')
return false;
}
return true;
}
How to calculate the date difference from client side using javascript?
Now we are going to find the difference between two date fields from the client side javascript or jquery. In some of the scenario, we need to find the number of days between two selected dates  like leave applying modules, hotel room booking etc. In this case we can simply calculate the difference between from date and to date using following function in javascript.
Here we are having two date fields for from date and todate. User has to select a from date and to date by using this controls. Todate should be greater than from date. When user select from date or todate we will call javascript function calculate()  and this function finds the difference between two dates and display the difference in the label. Its also validate as todate should be greater than the from date.
function calculate() {
var value1 = document.getElementById('<%=txtDateFrom.ClientID%>')
.value.split("/");
var value2 = document.getElementById('<%=txtDateTo.ClientID%>')
.value.split("/");
if (value1 != "" && value2 != "") {
var day1 = parseFloat(value1[0]);
var month1 = parseFloat(value1[1]);
var year1 = parseFloat(value1[2]);
var day2 = parseFloat(value2[0]);
var month2 = parseFloat(value2[1]);
var year2 = parseFloat(value2[2]);

if ((year2 < year1) || (year2 == year1 && month2 < month1) || 
(year2 == year1 && month2 == month1 && day2 < day1)) {
alert('From Date should greater than Date From');
document.getElementById('<%=txtVacationDays.ClientID%>').innerHTML = "0";
return;
}                    
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
var fromDate = new Date(year1, month1 - 1, day1);
var toDate = new Date(year2, month2 - 1, day2);
// Convert both dates to milliseconds
var dateFrom = fromDate.getTime();
var dateTo = toDate.getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(dateTo - dateFrom)
// Convert back to days and return
var DiffDays = Math.round(difference_ms / ONE_DAY)
document.getElementById('<%=txtVacationDays.ClientID%>').innerHTML 
= parseFloat(DiffDays) + 1;
}
}
In order to call this javascript function on aspx textbox change event, we need to set attributes to the textbox on code behind as follows.
protected void Page_Load(object sender, EventArgs e)
{
    txtFromDate.Attributes.Add("Onchange", "calculate();");
    txtToDate.Attributes.Add("Onchange", "calculate();");
}
ASPX page having two date fields as follows :
<table>
 <tr>
 <td>
 First Date:
 <asp:TextBox runat="server" ID="txtFromDate" />
 (DD/MM/YYYY format)<br />
 Second Date: Date:
 <asp:TextBox runat="server" ID="txtToDate" />
 (DD/MM/YYYY format)<br />
 <center>
 <asp:Button runat="server" ID="btnCheck" Text="Check" 
 OnClientClick="return calculate();" />
 </center>
 </td>
 </tr>
</table>




Reference :

How to calculate difference between two dates in javascript/jquery

Comments

Popular Posts

SharePoint Interview Questions and Answers

Download Infopath Form Templates

How to get current logged user information using JavaScript ?

Steps to set Form based authentication (FBA) for SharePoint 2010

SharePoint Interview Questions and Answers II

Get List Items - JavaScript

Change Language for current user with JSOM in SharePoint Online

Cross Site List Rollup Web Part for SharePoint 2010

Hide Recently Modified Items

SharePoint 2010 CSS Chart