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