Nico Walsemann
Nico Walsemann

Reputation: 190

Converting TimeSpan to "hh:mm" higher than 23:59

im Capturing Worktime in a Timespan.

If the Timespan has a Span higher than 23:59 my convert to a hh:mm format will only do 23:59, after that it starts at 01:00 again.

I want to be able to Display 24:05 Hours My Conversion to a Decimal (24.08 Hours) works fine.

Any Suggestions where i go wrong? have been comparing string format since 2 Days, and i think i do smth fundamentally wrong

decimal:

string decimalHours = TimeSpan.FromSeconds(value.Dauer).TotalHours.ToString("0.00");

hh:mm :

string hhmmHours = TimeSpan.FromSeconds(value.Dauer).ToString(@"hh:mm");

Edit: For Clarification changed the times (dumb way to show things from me )

Upvotes: 0

Views: 1075

Answers (2)

Youp Bernoulli
Youp Bernoulli

Reputation: 5645

@dbraillon is right. And this is just a simple solution to achieve want you desire:

TimeSpan timeWorked = new(1, 0, 30, 0);

$"{Math.Floor(timeWorked.TotalHours)}:{timeWorked.Minutes}";

Round the total number of hours to the nearest integer towards zero with Math.Floor and take the minutes component of the TimeSpan for the number of minutes (no need to do any conversion on minutes).

Upvotes: 3

dbraillon
dbraillon

Reputation: 1752

You won't be able to format a TimeSpan object via .ToString(format) overload the way you'd like.

Look at Microsoft doc, hh format cannot exceed 23 :

hh The number of hours, which ranges from "00" to "23".

You will have to build the format you want using .TotalHours.

What about:

var ts = new TimeSpan(hours: 50, minutes: 10, seconds: 20);
var hours = Math.Truncate(ts.TotalHours);
var formatted = $"{hours}:{ts.Minutes}:{ts.Seconds}";
Console.WriteLine(formatted); // Display 50:10:20

You could even create an extension method.

Upvotes: 3

Related Questions