Blog/Format.cs 953 B · 26 lines · raw · history

1 namespace Blog;
2
3 /// <summary>
4 /// Short human renderings of numbers that would otherwise be printed raw.
5 /// </summary>
6 public static class Format
7 {
8 /// <summary>
9 /// A duration as the largest two units that carry information — "3d 4h", "1h 4m", "3m 20s",
10 /// "42s" — matching what the bot itself prints in chat. Null renders as "?", since a duration
11 /// we don't know is not the same as one of zero.
12 /// </summary>
13 public static string Duration(TimeSpan? span)
14 {
15 if (span is not { } value) return "?";
16 if (value < TimeSpan.Zero) value = TimeSpan.Zero;
17
18 return value switch
19 {
20 { TotalDays: >= 1 } => $"{(int)value.TotalDays}d {value.Hours}h",
21 { TotalHours: >= 1 } => $"{(int)value.TotalHours}h {value.Minutes}m",
22 { TotalMinutes: >= 1 } => $"{(int)value.TotalMinutes}m {value.Seconds}s",
23 _ => $"{(int)value.TotalSeconds}s"
24 };
25 }
26 }