liujiandao
2024-03-30 1e65185f0ecb8d4f8f1fd9ea822137e0c841a47f
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
package model
 
import (
    "database/sql/driver"
    "encoding/json"
    "fmt"
    "time"
)
 
type CustomTime time.Time
 
const ctLayout = "2006-01-02 15:04:05" // 想要的时间格式
 
func (ct *CustomTime) MarshalJSON() ([]byte, error) {
    return json.Marshal(time.Time(*ct).Format(ctLayout))
}
 
func (ct *CustomTime) UnmarshalJSON(b []byte) error {
    var s string
    if err := json.Unmarshal(b, &s); err != nil {
        return err
    }
 
    t, err := time.Parse(ctLayout, s)
    if err != nil {
        return err
    }
 
    *ct = CustomTime(t)
    return nil
}
 
// Scan 将数据库值扫描到Go中的CustomTime
func (ct *CustomTime) Scan(value interface{}) error {
    if value == nil {
        *ct = CustomTime(time.Time{})
        return nil
    }
    if t, ok := value.(time.Time); ok {
        *ct = CustomTime(t)
        return nil
    }
    return fmt.Errorf("can't scan %T into CustomTime", value)
}
 
// Value 将CustomTime的值转换为数据库值
func (ct CustomTime) Value() (driver.Value, error) {
    if time.Time(ct).IsZero() {
        return nil, nil
    }
    return time.Time(ct), nil
}