1
DateTime dt1 = DateTime.Parse(label1.Text);
DateTime dt2 = DateTime.Parse(label2.Text);
TimeSpan ts1 = dt2 - dt1;

DateTime dt3 = DateTime.Parse(label3.Text);
DateTime dt4 = DateTime.Parse(label4.Text);
TimeSpan ts2 = dt4 - dt3;


TimeSpan workTime = ts1 + ts2;

label5.Text = workTime.TotalHours.ToString();

So my question is how to modify this code snippet so that it converts the numbers it outputs from decimal to "hh:mm"?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Paludis
  • 69
  • 5
  • By using `ToString("hh:mm")`? – MakePeaceGreatAgain Mar 02 '17 at 12:11
  • @HimBromBeere Almost. You need to escape `:`. – Patrick Hofman Mar 02 '17 at 12:12
  • @PatrickHofman that's not correct because it will not show _total_ hours. If timespan is 1 day 2 hours - it will format as "02:00", not "26:00" (as I think OP wants). – Evk Mar 02 '17 at 12:14
  • @HimBromBeere you have to escape the `:` to `ToString("hh\\:mm")` or `ToString(@"hh\:mm")`. It would indeed be the simplest approach if we knew `workTime` won't be more than a day. – Jon Hanna Mar 02 '17 at 12:36
  • @Jon Hanna it won't be more than a day. in fact its exactly eight hours. But if i work longer than that i want the program to show me the overtime. – Paludis Mar 02 '17 at 12:49

2 Answers2

4

If you want to include total hours (so that it will convert whole days to hours too), you can do it like that:

String.Format("{0:D2}:{1:D2}", (int)workTime.TotalHours, workTime.Minutes);
Evk
  • 98,527
  • 8
  • 141
  • 191
0

From comment:

it won't be more than a day

Then

label5.Text = workTime.ToString(@"hh\:mm");

is simplest, and correct. If you aren't 100% sure it won't be more than a day then Evk's answer is the one to go with, as the above will display 25 hours as "01:00" while Evk's will render it correctly as "25:00".

Jon Hanna
  • 110,372
  • 10
  • 146
  • 251