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.
Grant thomas
source share