unix_time.go
1.1 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
package jtime
import (
"fmt"
"strconv"
"time"
)
type UnixTimeSecond time.Time
// MarshalJSON implements json.Marshaler.
func (t UnixTimeSecond) MarshalJSON() ([]byte, error) {
stamp := fmt.Sprintf("%d", time.Time(t).Unix())
return []byte(stamp), nil
}
// MarshalJSON implements json.Unmarshaler.
func (t UnixTimeSecond) UnmarshalJSON(v []byte) error {
str := string(v)
number, err := strconv.Atoi(str)
if err != nil {
return fmt.Errorf("时间类型需要使用时间戳传参:%w", err)
}
t = UnixTimeSecond(time.Unix(int64(number), 0))
return nil
}
type TimeToUnixMsec int64
// MarshalJSON implements json.Marshaler.
func (t TimeToUnixMsec) MarshalJSON() ([]byte, error) {
stamp := fmt.Sprintf("%d", t)
return []byte(stamp), nil
}
// MarshalJSON implements json.Unmarshaler.
func (t *TimeToUnixMsec) UnmarshalJSON(v []byte) error {
if len(v) < 2 {
*t = 0
return nil
}
str := string(v[1 : len(v)-1])
number, err := time.Parse(time.RFC3339, str)
if err != nil {
return fmt.Errorf("时间类型需要使用时间戳传参:%w", err)
}
*t = TimeToUnixMsec(number.Unix() * 1000)
return nil
}