Last active
October 21, 2020 17:37
-
-
Save mtherien/77f8a44d37774913dd33763efa9b1539 to your computer and use it in GitHub Desktop.
Timespan Helper
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
| // Source: http://www.blackbeltcoder.com/Articles/time/creating-a-user-friendly-timespan-string | |
| public static class TimeSpanHelper | |
| { | |
| /// <summary> | |
| /// Constructs a user-friendly string for this TimeSpan instance. | |
| /// </summary> | |
| public static string ToUserFriendlyString(this TimeSpan span) | |
| { | |
| const int DaysInYear = 365; | |
| const int DaysInMonth = 30; | |
| // Get each non-zero value from TimeSpan component | |
| var values = new List<string>(); | |
| // Number of years | |
| var days = span.Days; | |
| if (days >= DaysInYear) | |
| { | |
| var years = days / DaysInYear; | |
| values.Add(CreateValueString(years, "year")); | |
| days = days % DaysInYear; | |
| } | |
| // Number of months | |
| if (days >= DaysInMonth) | |
| { | |
| var months = days / DaysInMonth; | |
| values.Add(CreateValueString(months, "month")); | |
| days = days % DaysInMonth; | |
| } | |
| // Number of days | |
| if (days >= 1) | |
| { | |
| values.Add(CreateValueString(days, "day")); | |
| } | |
| // Number of hours | |
| if (span.Hours >= 1) | |
| { | |
| values.Add(CreateValueString(span.Hours, "hour")); | |
| } | |
| // Number of minutes | |
| if (span.Minutes >= 1) | |
| { | |
| values.Add(CreateValueString(span.Minutes, "minute")); | |
| } | |
| // Number of seconds (include when 0 if no other components included) | |
| if (span.Seconds >= 1 || values.Count == 0) | |
| { | |
| values.Add(CreateValueString(span.Seconds, "second")); | |
| } | |
| // Combine values into string | |
| var builder = new StringBuilder(); | |
| for (var i = 0; i < values.Count; i++) | |
| { | |
| if (builder.Length > 0) | |
| { | |
| builder.Append((i == (values.Count - 1)) ? " and " : ", "); | |
| } | |
| builder.Append(values[i]); | |
| } | |
| // Return result | |
| return builder.ToString(); | |
| } | |
| /// <summary> | |
| /// Constructs a string description of a time-span value. | |
| /// </summary> | |
| /// <param name="value">The value of this item</param> | |
| /// <param name="description">The name of this item (singular form)</param> | |
| private static string CreateValueString(int value, string description) | |
| { | |
| return $"{value:#,##0} {((value == 1) ? description : $"{description}s")}"; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment