-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.go
66 lines (52 loc) · 1.01 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
package gotils
import (
"strconv"
"time"
)
type Time time.Time
func Now() Time {
return Time(time.Now())
}
func FromUnix(sec int64) Time {
return Time(time.Unix(sec, 0))
}
func FromUnixMilli(sec int64) Time {
return Time(time.UnixMilli(sec))
}
func (t Time) Time() time.Time {
return time.Time(t)
}
func (t Time) MarshalJSON() ([]byte, error) {
unixTime := time.Time(t).Unix()
// do not go below zero:
if unixTime <= 0 {
unixTime = 0
}
return []byte(strconv.FormatInt(unixTime, 10)), nil
}
func (t *Time) UnmarshalJSON(s []byte) (err error) {
r := string(s)
q, err := strconv.ParseInt(r, 10, 64)
CheckNotFatal(err)
if err != nil {
return err
}
if q > 0 {
*(*time.Time)(t) = time.Unix(q, 0)
} else {
*(*time.Time)(t) = time.Time{}
}
return nil
}
func (t Time) Unix() int64 {
return time.Time(t).Unix()
}
func (t Time) UTC() time.Time {
return time.Time(t).UTC()
}
func (t Time) Local() time.Time {
return time.Time(t).Local()
}
func (t Time) String() string {
return t.UTC().String()
}