-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtime.go
More file actions
114 lines (99 loc) · 2.35 KB
/
time.go
File metadata and controls
114 lines (99 loc) · 2.35 KB
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
package json
import (
jsoniter "github.com/json-iterator/go"
"reflect"
"time"
"unsafe"
)
var (
timeType = reflect.TypeOf(Time{})
)
type Time struct {
Hour int
Minutes int
Second int
}
func NewTime(hour int, minutes int, second int) Time {
return Time{Hour: hour, Minutes: minutes, Second: second}
}
func TimeOf(t time.Time) Time {
return NewTime(t.Hour(), t.Minute(), t.Second())
}
func (t Time) IsZero() (ok bool) {
ok = t.Hour == 0 && t.Minutes == 0 && t.Second == 0
return
}
func (t Time) ToTime() time.Time {
if t.Hour < 0 || t.Hour > 23 {
t.Hour = 0
}
if t.Minutes < 0 || t.Minutes > 59 {
t.Minutes = 0
}
if t.Second < 0 || t.Second > 59 {
t.Second = 0
}
return time.Date(1, 1, 1, t.Hour, t.Minutes, t.Second, 0, time.Local)
}
func (t Time) String() string {
return t.ToTime().Format("15:04:05")
}
func timeTypeEncoderFunc(ptr unsafe.Pointer, stream *jsoniter.Stream) {
v := reflect.NewAt(timeType, ptr).Elem().Interface().(Time)
if v.IsZero() {
stream.WriteString("")
} else {
stream.WriteString(v.ToTime().Format("15:04:05"))
}
return
}
func timeIsEmpty(ptr unsafe.Pointer) bool {
return reflect.NewAt(timeType, ptr).Elem().Interface().(Time).IsZero()
}
func timeTypeDecoderFunc(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
str := iter.ReadString()
if iter.Error != nil {
return
}
if str == "" {
return
}
v, parseErr := time.Parse("15:04:05", str)
if parseErr != nil {
iter.ReportError("unmarshal json.Time", parseErr.Error())
return
}
reflect.NewAt(timeType, ptr).Elem().Set(reflect.ValueOf(v))
return
}
var (
datetimeType = reflect.TypeOf(time.Time{})
)
func datetimeTypeEncoderFunc(ptr unsafe.Pointer, stream *jsoniter.Stream) {
v := reflect.NewAt(datetimeType, ptr).Elem().Interface().(time.Time)
if v.IsZero() {
stream.WriteString("")
} else {
stream.WriteString(v.Format(time.RFC3339))
}
return
}
func datetimeIsEmpty(ptr unsafe.Pointer) bool {
return reflect.NewAt(datetimeType, ptr).Elem().Interface().(time.Time).IsZero()
}
func datetimeTypeDecoderFunc(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
str := iter.ReadString()
if iter.Error != nil {
return
}
if str == "" {
return
}
v, parseErr := time.Parse(time.RFC3339, str)
if parseErr != nil {
iter.ReportError("unmarshal time.Time", parseErr.Error())
return
}
reflect.NewAt(datetimeType, ptr).Elem().Set(reflect.ValueOf(v))
return
}