Last active
October 24, 2024 21:24
-
-
Save mrkmg/dd3faf178d7e2e35e9405576894aaead to your computer and use it in GitHub Desktop.
C# .NET TimeSpan Rounding and Display
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
using System; | |
namespace Utils { | |
public static class TimeSpanExtensions | |
{ | |
public static TimeSpan Round(this TimeSpan span, TimeSpanRoundingType type, MidpointRounding mode = MidpointRounding.ToEven) => | |
type switch | |
{ | |
TimeSpanRoundingType.QuarterMinute => TimeSpan.FromSeconds(Math.Round(span.TotalSeconds / 15, 0, mode) * 15), | |
TimeSpanRoundingType.HalfMinute => TimeSpan.FromSeconds(Math.Round(span.TotalSeconds / 30, 0, mode) * 30), | |
TimeSpanRoundingType.Minute => TimeSpan.FromSeconds(Math.Round(span.TotalSeconds / 60, 0, mode) * 60), | |
TimeSpanRoundingType.QuarterHour => TimeSpan.FromMinutes(Math.Round(span.TotalMinutes / 15, 0, mode) * 15), | |
TimeSpanRoundingType.HalfHour => TimeSpan.FromMinutes(Math.Round(span.TotalMinutes / 30, 0, mode) * 30), | |
TimeSpanRoundingType.Hour => TimeSpan.FromMinutes(Math.Round(span.TotalMinutes / 60, 0, mode) * 60), | |
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null) | |
}; | |
public static string ToPrettyString(this TimeSpan span, TimeSpanPrettyDepth depth = TimeSpanPrettyDepth.Seconds) | |
{ | |
static string AddS(int i) => i > 1 ? "s" : string.Empty; | |
if (span == TimeSpan.Zero) return "no time"; | |
var sb = new StringBuilder(); | |
if (span.Days > 0 && depth >= TimeSpanPrettyDepth.Days) | |
sb.Append($"{span.Days} day{AddS(span.Days)} "); | |
if (span.Hours > 0 && depth >= TimeSpanPrettyDepth.Hours) | |
sb.Append($"{span.Hours} hour{AddS(span.Hours)} "); | |
if (span.Minutes > 0 && depth >= TimeSpanPrettyDepth.Minutes) | |
sb.Append($"{span.Minutes} minute{AddS(span.Minutes)} "); | |
if (span.Seconds > 0 && depth >= TimeSpanPrettyDepth.Seconds) | |
sb.Append($"{span.Seconds} second{AddS(span.Seconds)} "); | |
if (span.Milliseconds > 0 && depth >= TimeSpanPrettyDepth.Milliseconds) | |
sb.Append($"{span.Milliseconds} millisecond{AddS(span.Milliseconds)} "); | |
return sb.Remove(sb.Length - 1, 1).ToString(); | |
} | |
} | |
public enum TimeSpanRoundingType | |
{ | |
QuarterMinute, | |
HalfMinute, | |
Minute, | |
QuarterHour, | |
HalfHour, | |
Hour, | |
} | |
public enum TimeSpanPrettyDepth | |
{ | |
Days = 1, | |
Hours = 2, | |
Minutes = 3, | |
Seconds = 4, | |
Milliseconds = 5 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment