views:

121

answers:

3

I'd like an easy way to display any TimeSpan as an elapsed time without using loops or custom logic
e.g.

hours : minutes : seconds

I'm sure there must be a .NET built-in or format string that applies, however I'm unable to locate it.

+2  A: 

What's wrong with TimeSpan.ToString()?

EDIT: You can use a DateTime as an intermediate formatting store:

TimeSpan a = new TimeSpan(1, 45, 33);
string s = string.Format("{0:H:mm:ss}", new DateTime(a.Ticks));
Console.WriteLine(s);

Not pretty but works.

CesarGon
Wouldn't ToString display milliseconds aswell?
James
Because I'm often getting fractions of seconds like `1:45:33.5060000`
John K
You will if your TimeSpan contains fractions of seconds, yes. I am editing my answer with a workaround.
CesarGon
The edited version displays `12:00:43` instead of `00:00:43`.
John K
@jdk: fixed that by using "H" rather than "h" in format string.
CesarGon
+2  A: 

The question itself isn't a duplicate but the answer, I assume, is what you are looking for - Custom format Timespan with String.Format. To simplify your solution further you could wrap that functionality up in an extension method of Timespan.

James
No extension methods in .NET 2.0
John K
A: 

Here is a method I use for custom formatting:

TimeSpan Elapsed = TimeSpan.FromSeconds(5025);
string Formatted = String.Format("{0:0}:{1:00}:{2:00}",
    Math.Floor(Elapsed.TotalHours), Elapsed.Minutes, Elapsed.Seconds);
// result: "1:23:45"

I don't know if that qualifies as "without custom logic," but it is .NET 3.5 compatible and doesn't involve a loop.

JYelton