Saturday, July 28

How to calculate difference between two dates using JQuery?

In the following example I have discussed about calculating the difference between two days. Here, I have taken three text boxes, two are for entering "from date" and "to date". The third one is meant for showing the result after calculating the difference between those two days.

.aspx Page :(Source)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DateDifference.aspx.cs"Inherits="pages_DateDifference" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""">
<html xmlns="">
<head runat="server">   
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <table class="style1">
                    <asp:Label ID="lblFromDate" runat="server" Text="From Date:"></asp:Label>
                    <asp:TextBox ID="txtFromDate" runat="server"></asp:TextBox>
                    <asp:CalendarExtender ID="calFromDate" runat="server"TargetControlID="txtFromDate" PopupButtonID="txtFromDate" Format="dd/MM/yyyy">
                    <asp:Label ID="lblToDate" runat="server" Text="To Date :"></asp:Label>
                    <asp:TextBox ID="txtToDate" runat="server"></asp:TextBox>
                    <asp:CalendarExtender ID="calToDate" runat="server"TargetControlID="txtToDate" PopupButtonID="txtToDate"
                    <asp:Label ID="lblDifference" runat="server" Text="Total Days :"></asp:Label>
                    <asp:TextBox ID="txtDifference" runat="server"></asp:TextBox>

.aspx Page :(Design)

JQuery Method

<script type="text/javascript">
        function DateDifference() {
            //To check if both From Date and To Date are not null
            if ($("#txtFromDate").val() != '' && $("#txtToDate").val() != '') {
            // To convert the entered Date string (dd/MM/yyyy) to a valid date format(yyyy,MM,dd)
                var FromDateArr = $("#txtFromDate").val().split('/');
                var FromDate = new Date(FromDateArr[2], FromDateArr[1], FromDateArr[0]);
                var ToDateArr = $("#txtToDate").val().split('/');
                var ToDate = new Date(ToDateArr[2], ToDateArr[1], ToDateArr[0]);
                if (ToDate >= FromDate) {
                    var Differnece = new Date(ToDate - FromDate);
                    $("#txtDifference").val((Differnece.getTime() / 86400000) + 1);

Then call the 'DateDifference()' method in 'onchange' event of the text boxes: 

<asp:TextBox ID="txtFromDate" runat="server" onchange='DateDifference();'></asp:TextBox>

<asp:TextBox ID="txtToDate" runat="server" onchange='DateDifference();'></asp:TextBox>


Thanks Shibashish Mohanty

No comments:

Post a Comment

Please don't spam, spam comments is not allowed here.

shibashish mohanty