-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtime.go
More file actions
86 lines (73 loc) · 1.96 KB
/
time.go
File metadata and controls
86 lines (73 loc) · 1.96 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
78
79
80
81
82
83
84
85
86
package nulltypes
import (
"database/sql/driver"
"encoding/json"
"time"
)
// TruncateOff the degree of precision to REMOVE
// Default time.Microsecond
var TruncateOff = time.Microsecond
// DatabaseLocation is local the timezone
// the database is set to default UTC
var DatabaseLocation, _ = time.LoadLocation("UTC")
// NullTime is a wrapper around time.Time
type NullTime struct {
Time time.Time
Valid bool `default:"false"`
}
// Time method to get NullTime object from time.Time
func Time(Time time.Time) NullTime {
return NullTime{Time, true}
}
// MarshalJSON method is called by json.Marshal,
// whenever it is of type NullTime
func (nt NullTime) MarshalJSON() ([]byte, error) {
if !nt.Valid {
return json.Marshal(nil)
}
return json.Marshal(nt.Time)
}
// UnmarshalJSON method is called by json.Unmarshal,
// whenever it is of type NullTime
func (nt *NullTime) UnmarshalJSON(b []byte) error {
var t *time.Time
if err := json.Unmarshal(b, &t); err != nil {
return err
}
if t != nil {
nt.Valid = true
nt.Time = *t
} else {
nt.Valid = false
}
return nil
}
// Scan satisfies the sql.scanner interface
func (nt *NullTime) Scan(value interface{}) error {
rt, ok := value.(time.Time)
if ok {
*nt = NullTime{ToDatabaseFormat(rt), true}
} else {
*nt = NullTime{time.Time{}, false}
}
return nil
}
// Value satisfies the driver.Value interface
func (nt NullTime) Value() (driver.Value, error) {
if nt.Valid {
return nt.Time, nil
}
return nil, nil
}
// Now wrapper around the time.Now() function
func Now() NullTime {
return NullTime{ToDatabaseFormat(time.Now()), true}
}
// Date wrapper around the time.Date() function
func Date(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) NullTime {
return NullTime{ToDatabaseFormat(time.Date(year, month, day, hour, min, sec, nsec, loc)), true}
}
// insure the correct ToDatabaseFormat
func ToDatabaseFormat(t time.Time) time.Time {
return t.In(DatabaseLocation).Truncate(TruncateOff)
}