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.
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:
To calculate the Years between the two dates use:
To calculate the months between the two dates use:
To calculate the Total months between the two dates use:
To calculate the Total days, hours, minutes, seconds and milliseconds between two dates use:
To assign result values back to the td tags use the following code:
Now in default.aspx.cs the entire code will look such as follows:
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
- 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.
SummaryFrom 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.