Duration Calculator Between Two Dates Using ASP.Net C#

Background

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.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body style="background-color: #000080">  
  10.     <form id="form1" runat="server">  
  11.     <asp:ScriptManager ID="ScriptManager1" runat="server">  
  12.     </asp:ScriptManager>  
  13.     <table style="padding: 30px; color: White; margin-top: 30px">  
  14.         <tr>  
  15.             <td>  
  16.                 From Date  
  17.             </td>  
  18.             <td>  
  19.                 <asp:TextBox ID="FromYearTxt" runat="server"></asp:TextBox>  
  20.                 <asp:CalendarExtender ID="FromYearTxt_CalendarExtender" runat="server" Enabled="True"  
  21.                     TargetControlID="FromYearTxt" Format="dd/MM/yyyy">  
  22.                 </asp:CalendarExtender>  
  23.             </td>  
  24.             <td>  
  25.                 To Date  
  26.             </td>  
  27.             <td>  
  28.                 <asp:TextBox ID="ToYearTxt" runat="server"></asp:TextBox>  
  29.                 <asp:CalendarExtender ID="ToYearTxt_CalendarExtender" runat="server" Enabled="True"  
  30.                     TargetControlID="ToYearTxt">  
  31.                 </asp:CalendarExtender>  
  32.             </td>  
  33.         </tr>  
  34.     </table>  
  35.     <div style="margin-left: 180px">  
  36.         <asp:Button ID="btncalculate" runat="server" Text="Calculate" OnClick="btncalculate_Click" />  
  37.     </div>  
  38.     <table style="background-color: #0000FF; color: White; padding: 30px; margin-top: 20px;  
  39.         margin-left: 15px" id="tblResults" runat="server">  
  40.         <tr>  
  41.             <td>  
  42.                 Years  
  43.             </td>  
  44.             <td id="tdYear" runat="server">  
  45.             </td>  
  46.         </tr>  
  47.         <tr>  
  48.             <td>  
  49.                 Total Months  
  50.             </td>  
  51.             <td id="tdMonths" runat="server">  
  52.             </td>  
  53.         </tr>  
  54.         <tr>  
  55.             <td>  
  56.                 Total Days  
  57.             </td>  
  58.             <td id="tdDays" runat="server">  
  59.             </td>  
  60.         </tr>  
  61.         <tr>  
  62.             <td>  
  63.                 Total Hours  
  64.             </td>  
  65.             <td id="tdHrs" runat="server">  
  66.             </td>  
  67.         </tr>  
  68.         <tr>  
  69.             <td>  
  70.                 Total Minutes  
  71.             </td>  
  72.             <td id="tdminuts" runat="server">  
  73.             </td>  
  74.         </tr>  
  75.         <tr>  
  76.             <td>  
  77.                 Total Seconds  
  78.             </td>  
  79.             <td id="tdseconds" runat="server">  
  80.             </td>  
  81.         </tr>  
  82.         <tr>  
  83.             <td>  
  84.                 Total MileSesonds  
  85.             </td>  
  86.             <td id="tdmileSec" runat="server">  
  87.             </td>  
  88.         </tr>  
  89.     </table>  
  90.     </form>  
  91. </body>  
  92. </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:
  1. //Storing input Dates  
  2.  DateTime FromYear = Convert.ToDateTime(FromYearTxt.Text);  
  3.  DateTime ToYear = Convert.ToDateTime(ToYearTxt.Text); 
 To calculate the Years between the two dates use:
  1. //years  
  2. int Years = ToYear.Year - FromYear.Year; 
To calculate the months between the two dates use:
  1. //months  
  2.  int month = ToYear.Month - FromYear.Month; 
 To calculate the Total months between the two dates use:
  1. //Total Months  
  2.    int TotalMonths = (Years * 12) + month; 

To calculate the Total days, hours, minutes, seconds and milliseconds between two dates use:
  1.  //Creating object of TimeSpan Class  
  2. TimeSpan objTimeSpan = ToYear - FromYear;  
  3. //Total Hours  
  4.  double TotalHours = objTimeSpan.TotalHours;  
  5.   //Total Minutes  
  6. double TotalMinutes = objTimeSpan.TotalMinutes;  
  7.    //Total Seconds  
  8.  double TotalSeconds = objTimeSpan.TotalSeconds;  
  9.     //Total Mile Seconds  
  10.  double TotalMileSeconds = objTimeSpan.TotalMilliseconds; 
To assign result values back to the td tags use the following code:
  1. //Assining values to td tags  
  2.   tdYear.InnerText = Years + "  Year  " + month + "  Months";  
  3.   tdMonths.InnerText = Convert.ToString(TotalMonths);  
  4.   tdDays.InnerText = Convert.ToString(Days);  
  5.   tdHrs.InnerText = Convert.ToString(TotalHours);  
  6.   tdminuts.InnerText = Convert.ToString(TotalMinutes);  
  7.   tdseconds.InnerText = Convert.ToString(TotalSeconds);  
  8.   tdmileSec.InnerText = Convert.ToString(TotalMileSeconds); 
 Now in default.aspx.cs the entire code will look such as follows:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7.   
  8. public partial class _Default : System.Web.UI.Page  
  9. {  
  10.     protected void Page_Load(object sender, EventArgs e)  
  11.     {  
  12.         tblResults.Visible = false;  
  13.     }  
  14.     protected void btncalculate_Click(object sender, EventArgs e)  
  15.     {  
  16.         if (FromYearTxt.Text != "" && ToYearTxt.Text != "")  
  17.         {  
  18.             //Storing input Dates  
  19.             DateTime FromYear = Convert.ToDateTime(FromYearTxt.Text);  
  20.             DateTime ToYear = Convert.ToDateTime(ToYearTxt.Text);  
  21.   
  22.           //Creating object of TimeSpan Class  
  23.             TimeSpan objTimeSpan = ToYear - FromYear;  
  24.             //years  
  25.             int Years = ToYear.Year - FromYear.Year;  
  26.             //months  
  27.             int month = ToYear.Month - FromYear.Month;  
  28.             //TotalDays  
  29.             double Days = Convert.ToDouble(objTimeSpan.TotalDays);  
  30.             //Total Months  
  31.             int TotalMonths = (Years * 12) + month;  
  32.             //Total Hours  
  33.             double TotalHours = objTimeSpan.TotalHours;  
  34.             //Total Minutes  
  35.             double TotalMinutes = objTimeSpan.TotalMinutes;  
  36.             //Total Seconds  
  37.             double TotalSeconds = objTimeSpan.TotalSeconds;  
  38.             //Total Mile Seconds  
  39.             double TotalMileSeconds = objTimeSpan.TotalMilliseconds;  
  40.             //Assining values to td tags  
  41.             tdYear.InnerText = Years + "  Year  " + month + "  Months";  
  42.             tdMonths.InnerText = Convert.ToString(TotalMonths);  
  43.             tdDays.InnerText = Convert.ToString(Days);  
  44.             tdHrs.InnerText = Convert.ToString(TotalHours);  
  45.             tdminuts.InnerText = Convert.ToString(TotalMinutes);  
  46.             tdseconds.InnerText = Convert.ToString(TotalSeconds);  
  47.             tdmileSec.InnerText = Convert.ToString(TotalMileSeconds);  
  48.             tblResults.Visible = true;  
  49.         }  
  50.     }  

 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:
  • For detailed code please download the sample Zip file.
  • 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.

Next Recommended Readings