Date Difference Calculator Between Two Dates Using ASP.Net C#

I have read many forum posts regarding how to calculate duration between two dates, such as year, months, days and hours but no single post provided the proper solutions so I decided to. So let us start  creating a web application as:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New WebSite" - "C#" - "Empty WebSite" (to avoid adding a master page).
  3. Provide the web site a name such as "CalculateDuration"or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - Add  Web Form.
  5. Drag and drop one button and two textBoxes on the <form> section of the Default.aspx page.
  6. Add Ajax Calender Extender for two text boxes (optional). (If do not want to use a calender then enter date manually.)
  7. Now the default.aspx Page source code will look such as follows.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  %@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title></title>  
</head>  
<body style="background-color: #000080">  
    <form id="form1" runat="server">  
    <asp:ScriptManager ID="ScriptManager1" runat="server">  
    </asp:ScriptManager>  
    <table style="padding: 30px; color: White; margin-top: 30px">  
        <tr>  
            <td>  
                From Date  
            </td>  
            <td>  
                <asp:TextBox ID="FromYearTxt" runat="server"></asp:TextBox>  
                <asp:CalendarExtender ID="FromYearTxt_CalendarExtender" runat="server" Enabled="True"  
                    TargetControlID="FromYearTxt" Format="dd/MM/yyyy">  
                </asp:CalendarExtender>  
            </td>  
            <td>  
                To Date  
            </td>  
            <td>  
                <asp:TextBox ID="ToYearTxt" runat="server"></asp:TextBox>  
                <asp:CalendarExtender ID="ToYearTxt_CalendarExtender" runat="server" Enabled="True"  
                    TargetControlID="ToYearTxt">  
                </asp:CalendarExtender>  
            </td>  
        </tr>  
    </table>  
    <div style="margin-left: 180px">  
        <asp:Button ID="btncalculate" runat="server" Text="Calculate" OnClick="btncalculate_Click" />  
    </div>  
    <table style="background-color: #0000FF; color: White; padding: 30px; margin-top: 20px;  
        margin-left: 15px" id="tblResults" runat="server">  
        <tr>  
            <td>  
                Years  
            </td>  
            <td id="tdYear" runat="server">  
            </td>  
        </tr>  
        <tr>  
            <td>  
                Total Months  
            </td>  
            <td id="tdMonths" runat="server">  
            </td>  
        </tr>  
        <tr>  
            <td>  
                Total Days  
            </td>  
            <td id="tdDays" runat="server">  
            </td>  
        </tr>  
        <tr>  
            <td>  
                Total Hours  
            </td>  
            <td id="tdHrs" runat="server">  
            </td>  
        </tr>  
        <tr>  
            <td>  
                Total Minutes  
            </td>  
            <td id="tdminuts" runat="server">  
            </td>  
        </tr>  
        <tr>  
            <td>  
                Total Seconds  
            </td>  
            <td id="tdseconds" runat="server">  
            </td>  
        </tr>  
        <tr>  
            <td>  
                Total MileSesonds  
            </td>  
            <td id="tdmileSec" runat="server">  
            </td>  
        </tr>  
    </table>  
    </form>  
</body>  
</html>  
Now switch to design mode; it will look such as follows.
 
Now open the default.aspx page and add the following code in the calculate button click event.
Read two input TextBox texts and assign them to a DateTime data type variable as in the following:
//Storing input Dates  
 DateTime FromYear = Convert.ToDateTime(FromYearTxt.Text);  
 DateTime ToYear = Convert.ToDateTime(ToYearTxt.Text);
 To calculate the Years between the two dates use:
    //years  
    int Years = ToYear.Year - FromYear.Year; 
To calculate the months between the two dates use:
    //months  
     int month = ToYear.Month - FromYear.Month; 
 To calculate the Total months between the two dates use:
    //Total Months  
       int TotalMonths = (Years * 12) + month; 
To calculate the Total days, hours, minutes, seconds and milliseconds between two dates use:
//Creating object of TimeSpan Class  
TimeSpan objTimeSpan = ToYear - FromYear;  
//Total Hours  
 double TotalHours = objTimeSpan.TotalHours;  
  //Total Minutes  
double TotalMinutes = objTimeSpan.TotalMinutes;  
   //Total Seconds  
 double TotalSeconds = objTimeSpan.TotalSeconds;  
    //Total Mile Seconds  
 double TotalMileSeconds = objTimeSpan.TotalMilliseconds;  
To assign result values back to the td tags use the following code:
    //Assining values to td tags  
      tdYear.InnerText = Years + "  Year  " + month + "  Months";  
      tdMonths.InnerText = Convert.ToString(TotalMonths);  
      tdDays.InnerText = Convert.ToString(Days);  
      tdHrs.InnerText = Convert.ToString(TotalHours);  
      tdminuts.InnerText = Convert.ToString(TotalMinutes);  
      tdseconds.InnerText = Convert.ToString(TotalSeconds);  
      tdmileSec.InnerText = Convert.ToString(TotalMileSeconds); 
 Now in default.aspx.cs the entire code will look such as follows:
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.UI;  
    using System.Web.UI.WebControls;  
      
    public partial class _Default : System.Web.UI.Page  
    {  
        protected void Page_Load(object sender, EventArgs e)  
        {  
            tblResults.Visible = false;  
        }  
        protected void btncalculate_Click(object sender, EventArgs e)  
        {  
            if (FromYearTxt.Text != "" && ToYearTxt.Text != "")  
            {  
                //Storing input Dates  
                DateTime FromYear = Convert.ToDateTime(FromYearTxt.Text);  
                DateTime ToYear = Convert.ToDateTime(ToYearTxt.Text);  
      
              //Creating object of TimeSpan Class  
                TimeSpan objTimeSpan = ToYear - FromYear;  
                //years  
                int Years = ToYear.Year - FromYear.Year;  
                //months  
                int month = ToYear.Month - FromYear.Month;  
                //TotalDays  
                double Days = Convert.ToDouble(objTimeSpan.TotalDays);  
                //Total Months  
                int TotalMonths = (Years * 12) + month;  
                //Total Hours  
                double TotalHours = objTimeSpan.TotalHours;  
                //Total Minutes  
                double TotalMinutes = objTimeSpan.TotalMinutes;  
                //Total Seconds  
                double TotalSeconds = objTimeSpan.TotalSeconds;  
                //Total Mile Seconds  
                double TotalMileSeconds = objTimeSpan.TotalMilliseconds;  
                //Assining values to td tags  
                tdYear.InnerText = Years + "  Year  " + month + "  Months";  
                tdMonths.InnerText = Convert.ToString(TotalMonths);  
                tdDays.InnerText = Convert.ToString(Days);  
                tdHrs.InnerText = Convert.ToString(TotalHours);  
                tdminuts.InnerText = Convert.ToString(TotalMinutes);  
                tdseconds.InnerText = Convert.ToString(TotalSeconds);  
                tdmileSec.InnerText = Convert.ToString(TotalMileSeconds);  
                tblResults.Visible = true;  
            }  
        }  
    } 
 Now enter a From date and To date using the calender as in the following:
 
I have entered the following dates:
 
Now click on the Calculate button. It will display the following output:
 
Now from all the receding examples we have learned how to calculate the years, months, days, minutes, seconds & milliseconds between two dates
Note:
  • Do Proper Validation such as date input values when implementing.
  • Use the ScriptManager if you are using the Ajax Calender Extender that I used in the preceding demo application.
Summary
From all the examples above, we have learned how to calculate the duration between two dates. I hope this article is useful for all readers, if you have a suggestion then please contact me.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode