-
Notifications
You must be signed in to change notification settings - Fork 153
/
time.go
80 lines (67 loc) · 1.45 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
package values
import (
"time"
)
type Time int64
type Duration int64
const (
fixedWidthTimeFmt = "2006-01-02T15:04:05.000000000Z"
)
func ConvertTime(t time.Time) Time {
return Time(t.UnixNano())
}
func (t Time) Round(d Duration) Time {
if d <= 0 {
return t
}
r := t.Remainder(d)
if lessThanHalf(r, d) {
return t - Time(r)
}
return t + Time(d-r)
}
func (t Time) Truncate(d Duration) Time {
if d <= 0 {
return t
}
r := t.Remainder(d)
return t - Time(r)
}
func (t Time) Add(d Duration) Time {
return t + Time(d)
}
// remainder divides t by d and returns the remainder.
func (t Time) Remainder(d Duration) (r Duration) {
return Duration(int64(t) % int64(d))
}
// lessThanHalf reports whether x+x < y but avoids overflow,
// assuming x and y are both positive (Duration is signed).
func lessThanHalf(x, y Duration) bool {
return uint64(x)+uint64(x) < uint64(y)
}
func (t Time) String() string {
return t.Time().Format(fixedWidthTimeFmt)
}
func ParseTime(s string) (Time, error) {
t, err := time.Parse(fixedWidthTimeFmt, s)
if err != nil {
return 0, err
}
return ConvertTime(t), nil
}
func (t Time) Time() time.Time {
return time.Unix(0, int64(t)).UTC()
}
func (d Duration) Duration() time.Duration {
return time.Duration(d)
}
func (d Duration) String() string {
return time.Duration(d).String()
}
func ParseDuration(s string) (Duration, error) {
d, err := time.ParseDuration(s)
if err != nil {
return 0, err
}
return Duration(d), nil
}