Skip to content

Commit

Permalink
gtime: add FormatInterval (#880)
Browse files Browse the repository at this point in the history
* gtime: added FormatInterval

* improved comment
  • Loading branch information
gabor authored Jan 31, 2024
1 parent e0bf797 commit 94f94a8
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
32 changes: 32 additions & 0 deletions backend/gtime/gtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
20 changes: 20 additions & 0 deletions backend/gtime/gtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
})
}
}

0 comments on commit 94f94a8

Please sign in to comment.