Search code examples
c#formattingtimespan

Remove leading zeros from time to show elapsed time


I need to display simplest version of elapsed time span. Is there any ready thing to do that?

Samples:

HH:mm:ss
10:43:27 > 10h43m27s
00:04:12 > 4m12s
00:00:07 > 7s

I think I need a format provider for elapsed time.


Solution

  • Simple extension method should be enough:

    static class Extensions
    { 
        public static string ToShortForm(this TimeSpan t)
        {
            string shortForm = "";
            if (t.Hours > 0)
            {
                shortForm += string.Format("{0}h", t.Hours.ToString());
            }
            if (t.Minutes > 0)
            {
                shortForm += string.Format("{0}m", t.Minutes.ToString());
            }
            if (t.Seconds > 0)
            {
                shortForm += string.Format("{0}s", t.Seconds.ToString());
            }
            return shortForm;
        } 
    } 
    

    Test it with:

    TimeSpan tsTest = new TimeSpan(10, 43, 27);
    string output = tsTest.ToShortForm();
    tsTest = new TimeSpan(0, 4, 12);
    output = tsTest.ToShortForm();
    tsTest = new TimeSpan(0, 0, 7);
    output = tsTest.ToShortForm();