This repository has been archived by the owner on Mar 22, 2023. It is now read-only.
generated from things-labs/cicd-go-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimestamp.go
88 lines (70 loc) · 2.4 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
package extime
import (
"encoding/json"
"errors"
"time"
)
// UnixTimestamp unix 时间戳
type UnixTimestamp time.Time
// ToUnixTimestamp time.Time to UnixTimestamp
func ToUnixTimestamp(t time.Time) UnixTimestamp { return UnixTimestamp(t) }
// MarshalJSON implemented interface Marshaler
func (t UnixTimestamp) MarshalJSON() ([]byte, error) {
tt := time.Time(t)
if y := tt.Year(); y < 0 || y >= 10000 {
// RFC 3339 is clear that years are 4 digits exactly.
// See golang.org/issue/4556#c15 for more discussion.
return nil, errors.New("UnixTimestamp.MarshalJSON: year outside of range [0,9999]")
}
return json.Marshal(tt.Unix())
}
// UnmarshalJSON implemented interface Unmarshaler
func (t *UnixTimestamp) UnmarshalJSON(data []byte) error {
var sec int64
// Ignore null, like in the main JSON package.
if string(data) == "null" {
return nil
}
err := json.Unmarshal(data, &sec)
if err != nil {
return err
}
*t = UnixTimestamp(time.Unix(sec, 0))
return nil
}
// Time convert to standard time
func (t UnixTimestamp) StdTime() time.Time { return time.Time(t) }
// String implemented interface Stringer
func (t UnixTimestamp) String() string { return time.Time(t).String() }
// UnixNanoTimestamp unix nano 时间戳
type UnixNanoTimestamp time.Time
// ToUnixNanoTimestamp time.Time to UnixNanoTimestamp
func ToUnixNanoTimestamp(t time.Time) UnixNanoTimestamp { return UnixNanoTimestamp(t) }
// MarshalJSON implemented interface Marshaler
func (t UnixNanoTimestamp) MarshalJSON() ([]byte, error) {
tt := time.Time(t)
if y := tt.Year(); y < 0 || y >= 10000 {
// RFC 3339 is clear that years are 4 digits exactly.
// See golang.org/issue/4556#c15 for more discussion.
return nil, errors.New("UnixNanoTimestamp.MarshalJSON: year outside of range [0,9999]")
}
return json.Marshal(tt.UnixNano())
}
// UnmarshalJSON implemented interface Unmarshaler
func (t *UnixNanoTimestamp) UnmarshalJSON(data []byte) error {
var nano int64
// Ignore null, like in the main JSON package.
if string(data) == "null" {
return nil
}
err := json.Unmarshal(data, &nano)
if err != nil {
return err
}
*t = UnixNanoTimestamp(time.Unix(nano/int64(time.Second), nano%int64(time.Second)))
return nil
}
// StdTime convert to standard time
func (t UnixNanoTimestamp) StdTime() time.Time { return time.Time(t) }
// String implemented interface Stringer
func (t UnixNanoTimestamp) String() string { return time.Time(t).String() }