DarkW1nter DarkW1nter - 1 month ago 18
ASP.NET (C#) Question

Add hours and minutes from textbox values in ASP.Net (c#)

I have multpile textboxes holding calculated hours and minutes in the format HH:MM.
At the bottom of my page I need a final textbox to total these hours and minutes,should this be done using Timespan?

For clarification (and I know I haven't converted from string in the example below, this is just to show what I need to do)

txtTotalTime.Text = txtTimeTaken1.Text + txtTimeTaken2.Text + txtTimeTaken3.Text

Answer

You can use TimeSpan like this:

TimeSpan timeSpan = TimeSpan.Parse(txtTimeTaken1.Text) + TimeSpan.Parse(txtTimeTaken2.Text) + TimeSpan.Parse(txtTimeTaken3.Text);
txtTotalTime.Text  = string.Format("{0:00}:{1:00}", timeSpan.Hours, timeSpan.Minutes);

Use TimeSpan.Parse to parse your strings into TimeSpans, sum all of them and then format them back to HH:MM string using this method.

Comments