Monday 2 March 2015

C# TimeSpan format to always display "hh:mm:dd" safely

Introduction

TimeSpan class has a very convenient method of "ToString()" which converts the span to a fully-flavoured string of "[d.]hh:mm:ss[.ms]", but sometimes this comes too much. I needed a way to just cut off "ms" values as we didn't care about milliseconds in most cases. More than that, the "days" may be excessive as it makes it complex to calculate hours. Say, I needed a way to display, for instance, "1 day, 10 hours, 17 minutes, 36.789 seconds" of timespan value as "34:17:36". 

Microsoft did not give us a predefined format to achieve this simple goal - so I made this by myself. 

Implementation 

private static string GetFormattedTimeSpanString(TimeSpan timeSpan)
{
    const string TimeSpanFormat = "{0:D2}:{1:mm}:{1:ss}" ;                       // {0:D2} is to display at least two digits always 
    return string. Format( TimeSpanFormat, (int)timeSpan.TotalHours , timeSpan);// (int) casting is needed or it may display fraction
}

Test

public static void Main( string[] args)
{
    var timeSpans = new[]
  {
      new TimeSpan(99, 01, 01, 01, 99),
      TimeSpan. FromMilliseconds(12345),
      TimeSpan. FromSeconds(123456.789),
      TimeSpan. FromTicks(398583838521),
      TimeSpan. Zero
  };

  foreach ( var timeSpan in timeSpans)
  {
      Console. WriteLine( "Unformatted: " + timeSpan);
      Console. WriteLine( "Formatted: " + GetFormattedTimeSpanString(timeSpan));
      Console. WriteLine();
  }
}

Test Output



Evernote helps you remember everything and get organized effortlessly. Download Evernote.