Created
December 7, 2014 16:41
-
-
Save woodss/84ea5ab8f91816f92915 to your computer and use it in GitHub Desktop.
TimeSpan.ToFriendlyDisplay() i.e. "10 hours, 57 minutes, 37 seconds, 44 milliseconds"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class TimeSpanExtensions | |
{ | |
private enum TimeSpanElement | |
{ | |
Millisecond, | |
Second, | |
Minute, | |
Hour, | |
Day | |
} | |
public static string ToFriendlyDisplay(this TimeSpan timeSpan, int maxNrOfElements) | |
{ | |
maxNrOfElements = Math.Max(Math.Min(maxNrOfElements, 5), 1); | |
var parts = new[] | |
{ | |
Tuple.Create(TimeSpanElement.Day, timeSpan.Days), | |
Tuple.Create(TimeSpanElement.Hour, timeSpan.Hours), | |
Tuple.Create(TimeSpanElement.Minute, timeSpan.Minutes), | |
Tuple.Create(TimeSpanElement.Second, timeSpan.Seconds), | |
Tuple.Create(TimeSpanElement.Millisecond, timeSpan.Milliseconds) | |
} | |
.SkipWhile(i => i.Item2 <= 0) | |
.Take(maxNrOfElements); | |
return string.Join(", ", parts.Select(p => string.Format("{0} {1}{2}", p.Item2, p.Item1, p.Item2 > 1 ? "s" : string.Empty))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment