3

I have two textboxes that allow a user to enter a start time and an end time in this format (h:mm). I want it to return the difference in a label. For example, if a user enters 1:35 in the first textbox and 3:30 in the second textbox and press the 'Calculate' button, it will return the time 1:55.

Any ideas or resources for this? I only want to calculate the hour and minute difference between two textboxes. Date and seconds doesn't matter at all.

  • @Pierre-LucPineault, Not really a duplicate to linked question, The input values are different *(with AM,PM)* and that requires `DateTime` parsing. – Habib Feb 24 '14 at 18:29
  • @Habib The underlying problem is the same; there 2 time values, these values need to be parsed then subtracted. This question is only a simpler instance of the other one. – Pierre-Luc Pineault Feb 24 '14 at 18:36

2 Answers2

7

Parse both of the textboxes values to TimeSpan and then you can take their difference using -.

TimeSpan ts1 = TimeSpan.Parse(textBox1.Text); //"1:35"
TimeSpan ts2 = TimeSpan.Parse(textBox2.Text); //"3:30"

label.Text = (ts2 - ts1).ToString();         //"1:55:00"
Habib
  • 219,104
  • 29
  • 407
  • 436
  • @Habib : Is it possible to get the result like this : textbox1.Text=4/26/2015 5:39:09 AM AND textBox2.Text= 4/26/2015 5:45:24 AM. I want to get the result 6. (ie, I want to calculate the difference between time(5:39:09 - 5:45:24 )) – Reshma May 01 '15 at 11:17
  • @Reshma, it is possible, Parse the date strings to `DateTime` using `DateTime.Parse` or `ParseExact` and then do the subtraction. There are plenty of example for DateTime parsing and then taking their difference – Habib May 01 '15 at 14:37
2

If you cast the input as DateTime objects you can calculate the absolute time between them like so:

DateTime.Parse(startDate).Subtract(DateTime.Parse(endDate)).Duration().ToString("hh:mm");
mrtig
  • 2,217
  • 16
  • 26