-
Notifications
You must be signed in to change notification settings - Fork 0
/
timestamp.go
124 lines (102 loc) · 2.37 KB
/
timestamp.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
114
115
116
117
118
119
120
121
122
123
124
package time
import (
"database/sql"
"database/sql/driver"
"strconv"
"time"
)
type TimestampConstraints interface {
Timestamp(time.Time) int64
Time(int64) time.Time
}
type timestamp[T TimestampConstraints] int64
func (t timestamp[T]) Time() time.Time {
var v T
return v.Time(int64(t))
}
// Scan scan time.
func (t *timestamp[T]) Scan(value interface{}) (err error) {
var v T
nullTime := &sql.NullTime{}
err = nullTime.Scan(value)
*t = timestamp[T](v.Timestamp(nullTime.Time))
return
}
// Value get time value.
func (t timestamp[T]) Value() (driver.Value, error) {
var v T
return v.Time(int64(t)), nil
}
func (t timestamp[T]) MarshalJSON() ([]byte, error) {
return strconv.AppendInt(nil, int64(t), 10), nil
}
func (t *timestamp[T]) UnmarshalJSON(data []byte) error {
str := string(data)
if len(data) == 0 || str == "null" {
return nil
}
parseInt, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return err
}
*t = timestamp[T](parseInt)
return nil
}
// go生成的纳米级时间戳最后两位恒为0
type NanoTime struct{}
func (NanoTime) Encoding() *Encoding {
return &Encoding{
EncodeType: EncodeTypeUnixNanoseconds,
}
}
func (NanoTime) Timestamp(t time.Time) int64 {
return t.UnixNano()
}
func (NanoTime) Time(t int64) time.Time {
return time.Unix(0, t)
}
type MicroTime struct{}
func (MicroTime) Encoding() *Encoding {
return &Encoding{
EncodeType: EncodeTypeUnixMicroseconds,
}
}
func (MicroTime) Timestamp(t time.Time) int64 {
return t.UnixMicro()
}
func (MicroTime) Time(t int64) time.Time {
return time.UnixMicro(t)
}
type MilliTime struct{}
func (MilliTime) Encoding() *Encoding {
return &Encoding{
EncodeType: EncodeTypeUnixMilliseconds,
}
}
func (MilliTime) Timestamp(t time.Time) int64 {
return t.UnixMilli()
}
func (MilliTime) Time(t int64) time.Time {
return time.UnixMilli(t)
}
type SecondTime struct{}
func (SecondTime) Encoding() *Encoding {
return &Encoding{
EncodeType: EncodeTypeUnixSeconds,
}
}
func (SecondTime) Timestamp(t time.Time) int64 {
return t.Unix()
}
func (SecondTime) Time(t int64) time.Time {
return time.Unix(t, 0)
}
// 毫秒
type Timestamp = timestamp[MilliTime]
func NewTimeStamp(t time.Time) Timestamp {
return Timestamp(t.UnixMilli())
}
type SecondTimestamp = timestamp[SecondTime]
type MilliTimestamp = timestamp[MilliTime]
type MicroTimestamp = timestamp[MicroTime]
type NanoTimestamp = timestamp[NanoTime]