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 website 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 calendar 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. <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4. <html xmlns="http://www.w3.org/1999/xhtml">
  5. <head runat="server">
  6. <title></title>
  7. </head>
  8. <body style="background-color: #000080">
  9. <form id="form1" runat="server">
  10. <asp:ScriptManager ID="ScriptManager1" runat="server">
  11. </asp:ScriptManager>
  12. <table style="padding: 30px; color: White; margin-top: 30px">
  13. <tr>
  14. <td>
  15. From Date
  16. </td>
  17. <td>
  18. <asp:TextBox ID="FromYearTxt" runat="server"></asp:TextBox>
  19. <asp:CalendarExtender ID="FromYearTxt_CalendarExtender" runat="server" Enabled="True"
  20. TargetControlID="FromYearTxt" Format="dd/MM/yyyy">
  21. </asp:CalendarExtender>
  22. </td>
  23. <td>
  24. To Date
  25. </td>
  26. <td>
  27. <asp:TextBox ID="ToYearTxt" runat="server"></asp:TextBox>
  28. <asp:CalendarExtender ID="ToYearTxt_CalendarExtender" runat="server" Enabled="True"
  29. TargetControlID="ToYearTxt">
  30. </asp:CalendarExtender>
  31. </td>
  32. </tr>
  33. </table>
  34. <div style="margin-left: 180px">
  35. <asp:Button ID="btncalculate" runat="server" Text="Calculate" OnClick="btncalculate_Click" />
  36. </div>
  37. <table style="background-color: #0000FF; color: White; padding: 30px; margin-top: 20px;
  38. margin-left: 15px" id="tblResults" runat="server">
  39. <tr>
  40. <td>
  41. Years
  42. </td>
  43. <td id="tdYear" runat="server">
  44. </td>
  45. </tr>
  46. <tr>
  47. <td>
  48. Total Months
  49. </td>
  50. <td id="tdMonths" runat="server">
  51. </td>
  52. </tr>
  53. <tr>
  54. <td>
  55. Total Days
  56. </td>
  57. <td id="tdDays" runat="server">
  58. </td>
  59. </tr>
  60. <tr>
  61. <td>
  62. Total Hours
  63. </td>
  64. <td id="tdHrs" runat="server">
  65. </td>
  66. </tr>
  67. <tr>
  68. <td>
  69. Total Minutes
  70. </td>
  71. <td id="tdminuts" runat="server">
  72. </td>
  73. </tr>
  74. <tr>
  75. <td>
  76. Total Seconds
  77. </td>
  78. <td id="tdseconds" runat="server">
  79. </td>
  80. </tr>
  81. <tr>
  82. <td>
  83. Total MileSesonds
  84. </td>
  85. <td id="tdmileSec" runat="server">
  86. </td>
  87. </tr>
  88. </table>
  89. </form>
  90. </body>
  91. </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. public partial class _Default : System.Web.UI.Page
  8. {
  9. protected void Page_Load(object sender, EventArgs e)
  10. {
  11. tblResults.Visible = false;
  12. }
  13. protected void btncalculate_Click(object sender, EventArgs e)
  14. {
  15. if (FromYearTxt.Text != "" && ToYearTxt.Text != "")
  16. {
  17. //Storing input Dates
  18. DateTime FromYear = Convert.ToDateTime(FromYearTxt.Text);
  19. DateTime ToYear = Convert.ToDateTime(ToYearTxt.Text);
  20. //Creating object of TimeSpan Class
  21. TimeSpan objTimeSpan = ToYear - FromYear;
  22. //years
  23. int Years = ToYear.Year - FromYear.Year;
  24. //months
  25. int month = ToYear.Month - FromYear.Month;
  26. //TotalDays
  27. double Days = Convert.ToDouble(objTimeSpan.TotalDays);
  28. //Total Months
  29. int TotalMonths = (Years * 12) + month;
  30. //Total Hours
  31. double TotalHours = objTimeSpan.TotalHours;
  32. //Total Minutes
  33. double TotalMinutes = objTimeSpan.TotalMinutes;
  34. //Total Seconds
  35. double TotalSeconds = objTimeSpan.TotalSeconds;
  36. //Total Mile Seconds
  37. double TotalMileSeconds = objTimeSpan.TotalMilliseconds;
  38. //Assining values to td tags
  39. tdYear.InnerText = Years + " Year " + month + " Months";
  40. tdMonths.InnerText = Convert.ToString(TotalMonths);
  41. tdDays.InnerText = Convert.ToString(Days);
  42. tdHrs.InnerText = Convert.ToString(TotalHours);
  43. tdminuts.InnerText = Convert.ToString(TotalMinutes);
  44. tdseconds.InnerText = Convert.ToString(TotalSeconds);
  45. tdmileSec.InnerText = Convert.ToString(TotalMileSeconds);
  46. tblResults.Visible = true;
  47. }
  48. }
  49. }
Now enter a From date and To date using the calendar 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 preceding 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.