GORM 自定義time.time日期時間輸出格式

看一百次夜空里的深蓝發表於2024-03-13
 1 package helper
 2 
 3 import (
 4     "database/sql/driver"
 5     "encoding/json"
 6     "fmt"
 7     "time"
 8 )
 9 
10 const CUS_TIME_FORMAT = "2006-01-02 15:04:05"
11 
12 type CustomTime struct {
13     time.Time
14 }
15 
16 func (ct CustomTime) String() string {
17     return ct.Format(CUS_TIME_FORMAT)
18 }
19 
20 func (ct CustomTime) MarshalJSON() ([]byte, error) {
21     return []byte(`"` + ct.Format(CUS_TIME_FORMAT) + `"`), nil
22 }
23 
24 func (t *CustomTime) UnmarshalJSON(data []byte) error {
25     var timeStr string
26     err := json.Unmarshal(data, &timeStr)
27     if err != nil {
28         return err
29     }
30     parsedTime, err := time.Parse(CUS_TIME_FORMAT, timeStr)
31     if err != nil {
32         return err
33     }
34     *t = CustomTime{
35         parsedTime,
36     }
37     return nil
38 }
39 
40 func (ct *CustomTime) Scan(value interface{}) error {
41     switch v := value.(type) {
42     case time.Time:
43         ct.Time = v
44     case nil:
45         return nil
46     default:
47         return fmt.Errorf("unsupported Scan, storing driver.Value type %T into type *CustomTime", value)
48     }
49     return nil
50 }
51 
52 func (ct CustomTime) Value() (driver.Value, error) {
53     return ct.Time, nil
54 }

相關文章