-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.go
70 lines (62 loc) · 1.35 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
package nulls
import (
"database/sql"
"database/sql/driver"
"encoding/json"
"time"
)
// Time holds a nullable time.Time.
type Time struct {
// Time is the actual value when Valid.
Time time.Time `exhaustruct:"optional"`
// Valid when no NULL-value is represented.
Valid bool
}
// NewTime returns a valid Time with the given value.
func NewTime(t time.Time) Time {
return Time{
Time: t,
Valid: true,
}
}
// MarshalJSON marshals the time.Time. If not valid, a NULL-value is returned.
func (t Time) MarshalJSON() ([]byte, error) {
if !t.Valid {
return json.Marshal(nil)
}
return json.Marshal(t.Time)
}
// UnmarshalJSON as time.Time or sets Valid to false if null.
func (t *Time) UnmarshalJSON(data []byte) error {
if isNull(data) {
t.Valid = false
return nil
}
t.Valid = true
return json.Unmarshal(data, &t.Time)
}
// Scan to time.Time value or not valid if nil.
func (t *Time) Scan(src any) error {
var sqlTime sql.NullTime
err := sqlTime.Scan(src)
if err != nil {
return err
}
t.Valid = sqlTime.Valid
t.Time = sqlTime.Time
return nil
}
// Value returns the value for satisfying the driver.Valuer interface.
func (t Time) Value() (driver.Value, error) {
return sql.NullTime{
Time: t.Time,
Valid: t.Valid,
}.Value()
}
// UTC returns the UTC time.
func (t Time) UTC() Time {
return Time{
Time: t.Time.UTC(),
Valid: t.Valid,
}
}