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.

John K
  • 28,441
  • 31
  • 139
  • 229
  • I found this but I am pretty sure it's specific to .NET 4 http://msdn.microsoft.com/en-us/library/ee372287.aspx – Josh May 28 '10 at 22:48

5 Answers5

3

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
  • 15,099
  • 6
  • 57
  • 85
3

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.

Community
  • 1
  • 1
James
  • 80,725
  • 18
  • 167
  • 237
1

You can use:

TimeSpan t = TimeSpan.FromSeconds(999);
string s = t.ToString("c");  // s = "00:16:39"

For custom formats, see this MSDN page.

H H
  • 263,252
  • 30
  • 330
  • 514
0

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
  • 35,664
  • 27
  • 132
  • 191
0

Use This: .ToString()

According to MSDN, the default format this displays is [-][d.]hh:mm:ss[.fffffff]. This is the quickest and easiest way to display TimeSpan value as an elapsed time e.g. 1:45:33

If you have days, fractions of a second, or a negative value, use a custom format string as described in MSDN. This would look like .ToString(@"hh\:mm\:ss")

Example:

TimeSpan elapsed = new TimeSpan(0, 1, 45, 33);
Console.WriteLine(elapsed.ToString());             //outputs: "1:45:33"
Console.WriteLine(elapsed.ToString(@"hh\:mm\:ss"));//outputs: "1:45:33"
Bob
  • 686
  • 7
  • 7