CS Lewis
CS Lewis

Reputation: 489

Conversion to hh:mm (24-hour clock format) fails to work

Here is the information about my development environment:

I have C# code that need to display a duration of time as hh:mm (24-hour clock format)

I tried to use the TimeSpan.FromHours function.

String aTimSpn = TimeSpan.FromHours(70 - 19.083).ToString(@"hh\:mm");

The problem is that the aforementioned code gives a result of "02:55", but I was expecting "50:55" which would be 50 hours and 55 minutes.

How can I implement the code in such a way that I get the "50:55" result?

Upvotes: 0

Views: 84

Answers (1)

Ian
Ian

Reputation: 30813

Use TotalHours and Minutes (instead of immediately call ToString), and cast the TotalHours to int:

TimeSpan ts = TimeSpan.FromHours(70 - 19.083);
String aTimSpn = ((int)ts.TotalHours).ToString() + ":" + ts.Minutes.ToString();

Hours will give your TotalHours mod 24 (casted to int) result (which is 2) instead of the real total hours.

TotalHours will give you result including the fraction. Thus, use (int) casting to make it integer (50 instead of 50.917).

Upvotes: 1

Related Questions