Commit 912df2e2 by Carl Bergquist Committed by GitHub

gtime: some code style refactoring (#17369)

parent bc7c420e
...@@ -6,23 +6,26 @@ import ( ...@@ -6,23 +6,26 @@ import (
"time" "time"
) )
// ParseInterval parses and interval with support for all units that Grafana uses. var dateUnitPattern = regexp.MustCompile(`(\d+)([wdy])`)
// ParseInterval parses an interval with support for all units that Grafana uses.
func ParseInterval(interval string) (time.Duration, error) { func ParseInterval(interval string) (time.Duration, error) {
re := regexp.MustCompile(`(\d+)([wdy])`) result := dateUnitPattern.FindSubmatch([]byte(interval))
result := re.FindSubmatch([]byte(interval))
if len(result) != 3 {
if len(result) == 3 {
num, _ := strconv.Atoi(string(result[1]))
period := string(result[2])
if period == `d` {
return time.Hour * 24 * time.Duration(num), nil
} else if period == `w` {
return time.Hour * 24 * 7 * time.Duration(num), nil
} else {
return time.Hour * 24 * 7 * 365 * time.Duration(num), nil
}
} else {
return time.ParseDuration(interval) return time.ParseDuration(interval)
} }
num, _ := strconv.Atoi(string(result[1]))
period := string(result[2])
if period == `d` {
return time.Hour * 24 * time.Duration(num), nil
}
if period == `w` {
return time.Hour * 24 * 7 * time.Duration(num), nil
}
return time.Hour * 24 * 7 * 365 * time.Duration(num), nil
} }
...@@ -15,7 +15,9 @@ func TestParseInterval(t *testing.T) { ...@@ -15,7 +15,9 @@ func TestParseInterval(t *testing.T) {
}{ }{
{interval: "1d", duration: time.Hour * 24}, {interval: "1d", duration: time.Hour * 24},
{interval: "1w", duration: time.Hour * 24 * 7}, {interval: "1w", duration: time.Hour * 24 * 7},
{interval: "2w", duration: time.Hour * 24 * 7 * 2},
{interval: "1y", duration: time.Hour * 24 * 7 * 365}, {interval: "1y", duration: time.Hour * 24 * 7 * 365},
{interval: "5y", duration: time.Hour * 24 * 7 * 365 * 5},
{interval: "1M", err: errors.New("time: unknown unit M in duration 1M")}, {interval: "1M", err: errors.New("time: unknown unit M in duration 1M")},
{interval: "invalid-duration", err: errors.New("time: invalid duration invalid-duration")}, {interval: "invalid-duration", err: errors.New("time: invalid duration invalid-duration")},
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment