diff --git a/backend/gtime/gtime.go b/backend/gtime/gtime.go index 22e6eefb8..d34d378d2 100644 --- a/backend/gtime/gtime.go +++ b/backend/gtime/gtime.go @@ -85,3 +85,35 @@ func parse(inp string) (time.Duration, string, error) { return time.Duration(num), string(result[2]), nil } + +// FormatInterval converts a duration into the units that Grafana uses +func FormatInterval(inter time.Duration) string { + year := time.Hour * 24 * 365 + day := time.Hour * 24 + + if inter >= year { + return fmt.Sprintf("%dy", inter/year) + } + + if inter >= day { + return fmt.Sprintf("%dd", inter/day) + } + + if inter >= time.Hour { + return fmt.Sprintf("%dh", inter/time.Hour) + } + + if inter >= time.Minute { + return fmt.Sprintf("%dm", inter/time.Minute) + } + + if inter >= time.Second { + return fmt.Sprintf("%ds", inter/time.Second) + } + + if inter >= time.Millisecond { + return fmt.Sprintf("%dms", inter/time.Millisecond) + } + + return "1ms" +} diff --git a/backend/gtime/gtime_test.go b/backend/gtime/gtime_test.go index e9654321a..5c0efd3d8 100644 --- a/backend/gtime/gtime_test.go +++ b/backend/gtime/gtime_test.go @@ -100,3 +100,23 @@ func calculateDays5y() int { return daysInYear } + +func TestFormatInterval(t *testing.T) { + testCases := []struct { + name string + duration time.Duration + expected string + }{ + {"61s", time.Second * 61, "1m"}, + {"30ms", time.Millisecond * 30, "30ms"}, + {"23h", time.Hour * 23, "23h"}, + {"24h", time.Hour * 24, "1d"}, + {"367d", time.Hour * 24 * 367, "1y"}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.expected, FormatInterval(tc.duration)) + }) + } +}