durationDisplay formats a duration for easier display: - Durations of 24 hours or greater are displays as Xd - Durations less than 1 minute are displayed as <1m - Duration is truncated to the nearest minute - Empty minutes and seconds are truncated - The returned string is the absolute value. Use si
(d time.Duration)
| 42 | // if you need to indicate if the duration is positive or |
| 43 | // negative. |
| 44 | func durationDisplay(d time.Duration) string { |
| 45 | duration := d |
| 46 | sign := "" |
| 47 | if duration == 0 { |
| 48 | return "0s" |
| 49 | } |
| 50 | if duration < 0 { |
| 51 | duration *= -1 |
| 52 | } |
| 53 | // duration > 0 now |
| 54 | if duration < time.Minute { |
| 55 | return sign + "<1m" |
| 56 | } |
| 57 | if duration > 24*time.Hour { |
| 58 | duration = duration.Truncate(time.Hour) |
| 59 | } |
| 60 | if duration > time.Minute { |
| 61 | duration = duration.Truncate(time.Minute) |
| 62 | } |
| 63 | days := 0 |
| 64 | for duration.Hours() >= 24 { |
| 65 | days++ |
| 66 | duration -= 24 * time.Hour |
| 67 | } |
| 68 | durationDisplay := duration.String() |
| 69 | if days > 0 { |
| 70 | durationDisplay = fmt.Sprintf("%dd%s", days, durationDisplay) |
| 71 | } |
| 72 | for _, suffix := range []string{"m0s", "h0m", "d0s", "d0h"} { |
| 73 | if strings.HasSuffix(durationDisplay, suffix) { |
| 74 | durationDisplay = durationDisplay[:len(durationDisplay)-2] |
| 75 | } |
| 76 | } |
| 77 | return sign + durationDisplay |
| 78 | } |
| 79 | |
| 80 | // timeDisplay formats a time in the local timezone |
| 81 | // in RFC3339 format. |