-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
time.go
123 lines (109 loc) · 2.28 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
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
package nulltype
import (
"database/sql"
"database/sql/driver"
"encoding/json"
"time"
)
// NullTime is null friendly type for string.
type NullTime struct {
t time.Time
v bool // Valid is true if Time is not NULL
}
// NullTimeOf return NullTime that the value is set.
func NullTimeOf(value time.Time) NullTime {
var t NullTime
t.Set(value)
return t
}
// Valid return the value is valid. If true, it is not null value.
func (t *NullTime) Valid() bool {
return t.v
}
// TimeValue return the value.
func (t *NullTime) TimeValue() time.Time {
return t.t
}
// Reset set nil to the value.
func (t *NullTime) Reset() {
t.t = time.Unix(0, 0)
t.v = false
}
// Set set the value.
func (t *NullTime) Set(value time.Time) {
t.v = true
t.t = value
}
var timestampFormats = []string{
"2006-01-02 15:04:05.999999999-07:00",
"2006-01-02T15:04:05.999999999-07:00",
"2006-01-02 15:04:05.999999999",
"2006-01-02T15:04:05.999999999",
"2006-01-02 15:04:05",
"2006-01-02T15:04:05",
"2006-01-02 15:04",
"2006-01-02T15:04",
"2006-01-02",
"2006/01/02 15:04:05",
}
// Scan is a method for database/sql.
func (t *NullTime) Scan(value interface{}) error {
t.t, t.v = value.(time.Time)
if t.v {
return nil
}
var ns sql.NullString
if err := ns.Scan(value); err != nil {
return err
}
if !ns.Valid {
return nil
}
for _, tf := range timestampFormats {
if tt, err := time.Parse(tf, ns.String); err == nil {
t.t = tt
t.v = true
return nil
}
}
return nil
}
// Time return string indicated the value.
func (t NullTime) String() string {
if !t.v {
return ""
}
return t.t.Format("2006/01/02 15:04:05")
}
// MarshalJSON encode the value to JSON.
func (t NullTime) MarshalJSON() ([]byte, error) {
if !t.v {
return []byte("null"), nil
}
return json.Marshal(t.t.Format(time.RFC3339))
}
// UnmarshalJSON decode data to the value.
func (t *NullTime) UnmarshalJSON(data []byte) error {
var value *string
if err := json.Unmarshal(data, &value); err != nil {
return err
}
t.v = value != nil
if value == nil {
t.t = time.Unix(0, 0)
} else {
tt, err := time.Parse(time.RFC3339, *value)
if err != nil {
return err
}
t.t = tt
}
return nil
}
// Value implement driver.Valuer.
func (t NullTime) Value() (driver.Value, error) {
if !t.Valid() {
return nil, nil
}
return t.t, nil
}