Paludis
Paludis

Reputation: 69

Work time calc - How to convert decimal to "hh:mm"?

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"?

Upvotes: 1

Views: 505

Answers (2)

Jon Hanna
Jon Hanna

Reputation: 113242

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".

Upvotes: 0

Evk
Evk

Reputation: 101453

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);

Upvotes: 4

Related Questions