-
Notifications
You must be signed in to change notification settings - Fork 44
/
datetime_struct.go
91 lines (80 loc) · 2.16 KB
/
datetime_struct.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
package timeout
import (
"database/sql/driver"
"fmt"
"strings"
"time"
)
type DateTimeStruct struct {
time.Time
}
// UnmarshalText 通过 string 反序列化成 DateTime
// Author [SliverHorn](https://github.com/SliverHorn)
func (m *DateTimeStruct) UnmarshalText(value string) error {
dd, err := time.Parse(DateTimeFormat, value)
if err != nil {
return err
}
m.Time = dd
return nil
}
// UnmarshalTextByLayout 通过 string 序列化成 DateTime
// Author [SliverHorn](https://github.com/SliverHorn)
func (m *DateTimeStruct) UnmarshalTextByLayout(layout, value string) error {
dd, err := time.Parse(layout, value)
if err != nil {
return err
}
m.Time = dd
return nil
}
// ToDate DateTime 2 Date
// Author [SliverHorn](https://github.com/SliverHorn)
func (m *DateTimeStruct) ToDate() *DateStruct {
if m == nil {
return nil
}
return &DateStruct{Time: m.Time}
}
// UnmarshalJSON 反序列化
// Author [SliverHorn](https://github.com/SliverHorn)
func (m *DateTimeStruct) UnmarshalJSON(src []byte) error {
return m.UnmarshalText(strings.Replace(string(src), "\"", "", -1))
}
// MarshalJSON 序列化
// Author [SliverHorn](https://github.com/SliverHorn)
func (m *DateTimeStruct) MarshalJSON() ([]byte, error) {
return []byte(`"` + m.String() + `"`), nil
}
// String 输出 DateTime 变量为字符串
// Author [SliverHorn](https://github.com/SliverHorn)
func (m *DateTimeStruct) String() string {
return m.Format(DateTimeFormat)
}
// Scan 扫描
// Author [SliverHorn](https://github.com/SliverHorn)
func (m *DateTimeStruct) Scan(value interface{}) error {
switch v := value.(type) {
case []byte:
return m.UnmarshalText(string(v))
case string:
return m.UnmarshalText(v)
case time.Time:
m.Time = v
case nil:
*m = DateTimeStruct{}
default:
return fmt.Errorf("cannot sql.Scan() DBDate from: %#v", v)
}
return nil
}
// Value 值
// Author [SliverHorn](https://github.com/SliverHorn)
func (m *DateTimeStruct) Value() (driver.Value, error) {
return driver.Value(m.Format(DateTimeFormat)), nil
}
// GormDataType gorm 定义数据库字段类型
// Author [SliverHorn](https://github.com/SliverHorn)
func (m *DateTimeStruct) GormDataType() string {
return "DATETIME"
}