-
Notifications
You must be signed in to change notification settings - Fork 176
/
time.go
113 lines (92 loc) Β· 1.86 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package timeseries
import (
"encoding/json"
"fmt"
"strconv"
"time"
)
const (
Second = Duration(1)
Minute = Second * 60
Hour = Minute * 60
Day = Hour * 24
Month = Day * 30
)
type Context struct {
From Time `json:"from"`
To Time `json:"to"`
Step Duration `json:"step"`
}
type Duration int64
func (d Duration) Truncate(m Duration) Duration {
if m <= 0 {
return d
}
return d - d%m
}
func (d Duration) ToStandard() time.Duration {
return time.Duration(d) * time.Second
}
func (d Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(int64(d) * 1000)
}
func (d *Duration) UnmarshalJSON(b []byte) error {
var i int64
if err := json.Unmarshal(b, &i); err == nil {
*d = Duration(i / 1000)
return nil
}
var s string
if err := json.Unmarshal(b, &s); err == nil {
if td, err := time.ParseDuration(s); err == nil {
*d = Duration(td.Seconds())
return nil
}
}
return fmt.Errorf("invalid duration: %s", string(b))
}
type Time int64
func Now() Time {
return Time(time.Now().Unix())
}
func Since(t Time) Duration {
return Now().Sub(t)
}
func (t Time) IsZero() bool {
return t == 0
}
func (t Time) Truncate(d Duration) Time {
return t - t%Time(d)
}
func (t Time) Sub(other Time) Duration {
return Duration(t - other)
}
func (t Time) Add(d Duration) Time {
return t + Time(d)
}
func (t Time) Before(other Time) bool {
return t < other
}
func (t Time) After(other Time) bool {
return t > other
}
func (t Time) ToStandard() time.Time {
return time.Unix(int64(t), 0).UTC()
}
func (t Time) String() string {
return strconv.FormatInt(int64(t), 10)
}
func (t Time) MarshalJSON() ([]byte, error) {
if t == 0 {
return json.Marshal(nil)
}
return json.Marshal(int64(t) * 1000)
}
func (t *Time) UnmarshalJSON(b []byte) error {
var i int64
if err := json.Unmarshal(b, &i); err != nil {
return err
}
*t = Time(i / 1000)
return nil
}