-
Notifications
You must be signed in to change notification settings - Fork 0
/
datetime.go
98 lines (81 loc) · 1.91 KB
/
datetime.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
package time
import (
"database/sql"
"database/sql/driver"
"strconv"
"time"
)
type Date int64
func (d Date) Time() time.Time {
return time.Unix(int64(d), 0)
}
// Scan scan time.
func (d *Date) Scan(value interface{}) (err error) {
nullTime := &sql.NullTime{}
err = nullTime.Scan(value)
*d = Date(nullTime.Time.Unix())
return
}
// Value get time value.
func (d Date) Value() (driver.Value, error) {
return []byte(time.Unix(int64(d), 0).Format(time.DateOnly)), nil
}
func (d Date) MarshalJSON() ([]byte, error) {
return strconv.AppendInt(nil, int64(d), 10), nil
}
func (d *Date) UnmarshalJSON(data []byte) error {
str := string(data)
if len(data) == 0 || str == "null" {
return nil
}
if len(str) > 1 && str[0] == '"' && str[len(str)-1] == '"' {
str = str[1 : len(str)-1]
t, err := time.ParseInLocation(time.DateOnly, str, time.Local)
if err != nil {
return err
}
*d = Date(t.Unix())
return nil
}
return nil
}
func (ts Date) GormDataType() string {
return "time"
}
type DateTime int64
func (d DateTime) Time() time.Time {
return time.Unix(int64(d), 0)
}
// Scan scan time.
func (d *DateTime) Scan(value interface{}) (err error) {
nullTime := &sql.NullTime{}
err = nullTime.Scan(value)
*d = DateTime(nullTime.Time.Unix())
return
}
// Value get time value.
func (d DateTime) Value() (driver.Value, error) {
return time.Unix(int64(d), 0), nil
}
func (d DateTime) MarshalJSON() ([]byte, error) {
return []byte(time.Unix(int64(d), 0).Format(time.DateTime)), nil
}
func (d *DateTime) UnmarshalJSON(data []byte) error {
str := string(data)
if len(data) == 0 || str == "null" {
return nil
}
if len(str) > 1 && str[0] == '"' && str[len(str)-1] == '"' {
str = str[1 : len(str)-1]
t, err := time.ParseInLocation(time.DateTime, str, time.Local)
if err != nil {
return err
}
*d = DateTime(t.Unix())
return nil
}
return nil
}
func (ts DateTime) GormDataType() string {
return "time"
}