forked from grafana/grafana-plugin-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gtime.go
87 lines (74 loc) · 1.92 KB
/
gtime.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package gtime
import (
"fmt"
"regexp"
"strconv"
"time"
)
var dateUnitPattern = regexp.MustCompile(`^(\d+)([dwMy])$`)
// ParseInterval parses an interval with support for all units that Grafana uses.
// An interval is relative to the current wall time.
func ParseInterval(inp string) (time.Duration, error) {
dur, period, err := parse(inp)
if err != nil {
return 0, err
}
if period == "" {
return dur, nil
}
num := int(dur)
// Use UTC to ensure that the interval is deterministic, and daylight saving
// doesn't cause surprises
now := time.Now().UTC()
switch period {
case "d":
return now.AddDate(0, 0, num).Sub(now), nil
case "w":
return now.AddDate(0, 0, num*7).Sub(now), nil
case "M":
return now.AddDate(0, num, 0).Sub(now), nil
case "y":
return now.AddDate(num, 0, 0).Sub(now), nil
}
return 0, fmt.Errorf("invalid interval %q", inp)
}
// ParseDuration parses a duration with support for all units that Grafana uses.
// Durations are independent of wall time.
func ParseDuration(inp string) (time.Duration, error) {
dur, period, err := parse(inp)
if err != nil {
return 0, err
}
if period == "" {
return dur, nil
}
// The average number of days in a year, using the Julian calendar
const daysInAYear = 365.25
const day = 24 * time.Hour
const week = 7 * day
const year = time.Duration(float64(day) * daysInAYear)
const month = time.Duration(float64(year) / 12)
switch period {
case "d":
return dur * day, nil
case "w":
return dur * week, nil
case "M":
return dur * month, nil
case "y":
return dur * year, nil
}
return 0, fmt.Errorf("invalid duration %q", inp)
}
func parse(inp string) (time.Duration, string, error) {
result := dateUnitPattern.FindSubmatch([]byte(inp))
if len(result) != 3 {
dur, err := time.ParseDuration(inp)
return dur, "", err
}
num, err := strconv.Atoi(string(result[1]))
if err != nil {
return 0, "", err
}
return time.Duration(num), string(result[2]), nil
}