Created
November 2, 2021 16:04
-
-
Save DougBarry/563e93b324166c944e667d3f4b24e148 to your computer and use it in GitHub Desktop.
C# Timespan to human readable string extension method
This file contains hidden or 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
# Based on https://stackoverflow.com/a/41966914 | |
public static class ExtensionMethods | |
{ | |
public static string ToHumanReadable(this TimeSpan timeSpan) | |
{ | |
Func<Tuple<int, string>, string> tupleFormatter = t => $"{t.Item1} {t.Item2}{(t.Item1 == 1 ? string.Empty : "s")}"; | |
var components = new List<Tuple<int, string>> | |
{ | |
Tuple.Create((int) timeSpan.TotalDays, "day"), | |
Tuple.Create(timeSpan.Hours, "hour"), | |
Tuple.Create(timeSpan.Minutes, "minute"), | |
Tuple.Create(timeSpan.Seconds, "second"), | |
}; | |
components.RemoveAll(i => i.Item1 == 0); | |
string extra = ""; | |
if (components.Count > 1) | |
{ | |
var finalComponent = components[components.Count - 1]; | |
components.RemoveAt(components.Count - 1); | |
extra = $" and {tupleFormatter(finalComponent)}"; | |
} | |
return $"{string.Join(", ", components.Select(tupleFormatter))}{extra}"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment