Remove leading zeros from time to show elapsed time

I need to show the simplest version of the elapsed time interval. Is there any finished thing for this?

Examples:

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

I think I need a format provider in the past.

+7
source share
5 answers

A simple extension method should suffice:

 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(); 
+7
source

Here's a single line (almost) if you have a TimeSpan objectL

 (new TimeSpan(0, 0, 30, 21, 3)) .ToString(@"d\d\ hh\hmm\mss\s") .TrimStart(' ','d','h','m','s','0'); 

Code output

 30m21s 

The first line just makes the TimeSpan object for example, .ToString formats it in the requested format, and then .TrimStart removes leading characters that you don't need.

+4
source

I don't think this can be done in a simple way by creating a custom format serializer - I would just make my own:

 TimeSpan delta = TimeSpan.Parse("09:03:07"); string displayTime = string.Empty; if (delta.Hours > 0) displayTime += delta.Hours.ToString() + "h"; if (delta.Minutes > 0) displayTime += delta.Minutes.ToString() + "m"; if (delta.Seconds > 0) displayTime += delta.Seconds.ToString() + "s"; 

Please note that this will only work for positive time frames.

+3
source

You can use string.Format to achieve this, along with some conditional statements:

 public static string GetSimplestTimeSpan(TimeSpan timeSpan) { var result = string.Empty; if (timeSpan.Days > 0) { result += string.Format( @"{0:ddd\d}", timeSpan).TrimStart('0'); } if (timeSpan.Hours > 0) { result += string.Format( @"{0:hh\h}", timeSpan).TrimStart('0'); } if (timeSpan.Minutes > 0) { result += string.Format( @"{0:mm\m}", timeSpan).TrimStart('0'); } if (timeSpan.Seconds > 0) { result += string.Format( @"{0:ss\s}", timeSpan).TrimStart('0'); } return result; } 

Although, after seeing the answer from BrokenGlass, I am tempted to say that using Format here is generally not too great. However, this allows you to customize the output of each element of the elapsed time, if required.

+1
source

Here is my trick:

  Dim TimeTaken As String = TimeSpan.ToString("g") ' Supply TimeSpan If TimeTaken.Contains("0:00") Then TimeTaken = TimeTaken.Remove(0, 3) ElseIf TimeTaken.Contains("0:0") Then TimeTaken = TimeTaken.Remove(0, 2) End If 
+1
source

All Articles