-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtime.go
More file actions
77 lines (57 loc) · 1.1 KB
/
time.go
File metadata and controls
77 lines (57 loc) · 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
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
package nullish
import (
"bytes"
"database/sql/driver"
"errors"
"time"
"github.com/goccy/go-json"
)
type NullTime struct {
Time time.Time
Valid bool
}
// Value method
func (nt NullTime) Value() (driver.Value, error) {
if !nt.Valid {
return nil, nil
}
return nt.Time, nil
}
// Scan method
func (nt *NullTime) Scan(value interface{}) error {
if value == nil {
nt.Time, nt.Valid = time.Time{}, false
return nil
}
b, ok := value.(time.Time)
if !ok {
return errors.New("type assertion to time is failed")
}
nt.Time, nt.Valid = b, true
return nil
}
// MarshalJSON method
func (nt NullTime) MarshalJSON() ([]byte, error) {
if !nt.Valid {
return NullType, nil
}
return json.Marshal(nt.Time.Format(time.RFC3339Nano))
}
// UnmarshalJSON method
func (nt *NullTime) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, NullType) {
*nt = NullTime{}
return nil
}
var res string
err := json.Unmarshal(data, &res)
if err != nil {
return err
}
pTime, err := time.Parse(time.RFC3339Nano, res)
if err != nil {
return err
}
*nt = NullTime{Time: pTime, Valid: true}
return nil
}