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:
- "Start" - "All Programs" - "Microsoft Visual Studio 2010".
- "File" - "New WebSite" - "C#" - "Empty WebSite" (to avoid adding a master page).
- Provide the web site a name such as "CalculateDuration"or another as you wish and specify the location.
- Then right-click on Solution Explorer - "Add New Item" - Add Web Form.
- Drag and drop one button and two textBoxes on the <form> section of the Default.aspx page.
- Add Ajax Calender Extender for two text boxes (optional). (If do not want to use a calender then enter date manually.)
- 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:
-
- DateTime FromYear = Convert.ToDateTime(FromYearTxt.Text);
- DateTime ToYear = Convert.ToDateTime(ToYearTxt.Text);
To calculate the Years between the two dates use:
-
- int Years = ToYear.Year - FromYear.Year;
To calculate the months between the two dates use:
-
- int month = ToYear.Month - FromYear.Month;
To calculate the Total months between the two dates use:
-
- int TotalMonths = (Years * 12) + month;
To calculate the Total days, hours, minutes, seconds and milliseconds between two dates use:
-
- TimeSpan objTimeSpan = ToYear - FromYear;
-
- double TotalHours = objTimeSpan.TotalHours;
-
- double TotalMinutes = objTimeSpan.TotalMinutes;
-
- double TotalSeconds = objTimeSpan.TotalSeconds;
-
- double TotalMileSeconds = objTimeSpan.TotalMilliseconds;
To assign result values back to the td tags use the following code:
-
- 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 != "")
- {
-
- DateTime FromYear = Convert.ToDateTime(FromYearTxt.Text);
- DateTime ToYear = Convert.ToDateTime(ToYearTxt.Text);
-
-
- TimeSpan objTimeSpan = ToYear - FromYear;
-
- int Years = ToYear.Year - FromYear.Year;
-
- int month = ToYear.Month - FromYear.Month;
-
- double Days = Convert.ToDouble(objTimeSpan.TotalDays);
-
- int TotalMonths = (Years * 12) + month;
-
- double TotalHours = objTimeSpan.TotalHours;
-
- double TotalMinutes = objTimeSpan.TotalMinutes;
-
- double TotalSeconds = objTimeSpan.TotalSeconds;
-
- double TotalMileSeconds = objTimeSpan.TotalMilliseconds;
-
- 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:
- 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.