forked from influxdata/flux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.go
98 lines (87 loc) · 1.88 KB
/
time.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
88
89
90
91
92
93
94
95
96
97
98
package flux
import (
"math"
"time"
)
var (
MinTime = Time{
Absolute: time.Unix(0, math.MinInt64),
}
MaxTime = Time{
Absolute: time.Unix(0, math.MaxInt64),
}
Now = Time{
IsRelative: true,
}
)
// Time represents either a relative or absolute time.
// If Time is its zero value then it represents a time.Time{}.
// To represent the now time you must set IsRelative to true.
type Time struct {
IsRelative bool
Relative time.Duration
Absolute time.Time
}
// Time returns the time specified relative to now.
func (t Time) Time(now time.Time) time.Time {
if t.IsRelative {
return now.Add(t.Relative)
}
return t.Absolute
}
func (t Time) IsZero() bool {
return !t.IsRelative && t.Absolute.IsZero()
}
func (t *Time) UnmarshalText(data []byte) error {
if len(data) == 0 {
t.Absolute = time.Time{}
t.Relative = 0
t.IsRelative = false
return nil
}
str := string(data)
if str == "now" {
t.Relative = 0
t.Absolute = time.Time{}
t.IsRelative = true
return nil
}
d, err := time.ParseDuration(str)
if err == nil {
t.Relative = d
t.Absolute = time.Time{}
t.IsRelative = true
return nil
}
ts, err := time.Parse(time.RFC3339Nano, str)
if err != nil {
return err
}
t.Absolute = ts.UTC()
t.IsRelative = false
t.Relative = 0
return nil
}
func (t Time) MarshalText() ([]byte, error) {
if t.IsRelative {
if t.Relative == 0 {
return []byte("now"), nil
}
return []byte(t.Relative.String()), nil
}
return []byte(t.Absolute.Format(time.RFC3339Nano)), nil
}
// Duration is a marshalable duration type.
//TODO make this the real duration parsing not just time.ParseDuration
type Duration time.Duration
func (d *Duration) UnmarshalText(data []byte) error {
dur, err := time.ParseDuration(string(data))
if err != nil {
return err
}
*d = Duration(dur)
return nil
}
func (d Duration) MarshalText() ([]byte, error) {
return []byte(time.Duration(d).String()), nil
}