15

I have a timespan, ts, that has mostly minutes and seconds, but sometimes hours. I'd like ts to return a formatted string that'll give the following results:

3:30 (hours not displayed, showing only full minutes)
13:30 
1:13:30 (shows only full hours instead of 01:13:30)

So far I have:

string TimeSpanText = string.Format("{0:h\\:mm\\:ss}", MyTimeSpan);

but it's not giving the above results. How can I achieve the results I want?

Adrian Toman
  • 11,316
  • 5
  • 48
  • 62
frenchie
  • 51,731
  • 109
  • 304
  • 510

2 Answers2

14

Maybe you want something like

string TimeSpanText = string.Format(
    MyTimeSpan.TotalHours >= 1 ? @"{0:h\:mm\:ss}" : @"{0:mm\:ss}",
    MyTimeSpan); 
Gabe
  • 84,912
  • 12
  • 139
  • 238
6

I don't think a single format string will give you what you want, but building the output yourself is a simple task:

public string FormatTimeSpan(TimeSpan ts)
{
    var sb = new StringBuilder();

    if ((int) ts.TotalHours > 0)
    {
        sb.Append((int) ts.TotalHours);
        sb.Append(":");
    }

    sb.Append(ts.Minutes.ToString("m"));
    sb.Append(":");
    sb.Append(ts.Seconds.ToString("ss"));

    return sb.ToString();
}

EDIT: Better idea!

You could make the method above an extension method on the TimeSpan class like so:

public static class Extensions
{
    public static string ToMyFormat(this TimeSpan ts)
    {
        // Code as above.
    }
}

Then using this is as simple as invoking ts.ToMyFormat().

Ben
  • 6,023
  • 1
  • 25
  • 40
  • I love the idea of creating an extension method!! – frenchie Jan 17 '11 at 05:09
  • There is one little logic bug; if seconds are between 0 and 9, the output of 5 minutes and 3 seconds looks like 5:3 instead of 5:03. I'm working on it. Thanks for showing me how extension methods work; you read about them but when you build your own for the first time, you see how they really work for you. Thanks. – frenchie Jan 17 '11 at 05:18
  • Here's for the seconds:if (ts.Seconds < 10) { sb.Append(":0"); } else { sb.Append(":"); } – frenchie Jan 17 '11 at 05:20
  • Because `ts.Minutes` is an int, the code should be modified to read `ts.Minutes.ToString("d2")` – Dan Esparza Jul 31 '14 at 17:53