0

I need to compare two TimeSpan values bigger than 24 hours. For that I use the following code

string startTime = textBox1.Text;
string endTime = textBox21.Text;
TimeSpan startTimet = new TimeSpan(int.Parse(startTime.Split(':')[0]),    // hours
                      int.Parse(startTime.Split(':')[1]),    // minutes
                      0);
TimeSpan endTimet = new TimeSpan(int.Parse(endTime.Split(':')[0]),    // hours
                    int.Parse(endTime.Split(':')[1]),    // minutes
                    0);
TimeSpan duration = endTimet.Subtract(startTimet);
label29.Text = duration.ToString();

If the values aren't bigger than 24H it's all ok, but if I have a value bigger than 24h the TimeSpan will appear like DD.HH.MM.SS.

For example:

endTimet = 32:15

startTimet = 02:00

duration = 1.06:15:00

And what I really need is the normal format like HH:MM, assuming the hours are greater than 24, getting the expected 30:15

Can anyone help me here? Regards

Reznor13
  • 181
  • 17
  • Duplicate of http://stackoverflow.com/questions/3505230/format-timespan-greater-than-24-hour – dotNET Nov 05 '14 at 16:46
  • Dup link is *similar*, but not exactly the same as asked. – Matt Johnson-Pint Nov 05 '14 at 17:10
  • @MattJohnson: What difference do you see? The accepted answer of Jon does precisely what has been asked by the OP here. – dotNET Nov 05 '14 at 17:22
  • @dotNET - The technique is similar, yes. However the requested format is different. This question also involves parsing and subtraction, though one might argue those are extraneous to the question. It could go either way really, but in my mind it's not an *exact* duplicate. – Matt Johnson-Pint Nov 05 '14 at 17:26

2 Answers2

2

Perhaps with this workaround:

TimeSpan duration = TimeSpan.FromHours(30);
string result = string.Format("{0}:{1}"
    , duration.TotalHours
    , duration.Minutes);  // 30:00
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

Noda Time to the rescue!

string s1 = "123:45";
string s2 = "234:56";

DurationPattern p = DurationPattern.CreateWithInvariantCulture("H:mm");
Duration d1 = p.Parse(s1).Value;
Duration d2 = p.Parse(s2).Value;

Duration diff = d2 - d1;

string result = p.Format(diff);  // "111:11"
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575