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 string:
45 ct.Time, _ = time.Parse(CUS_TIME_FORMAT, value.(string))
46 case nil:
47 return nil
48 default:
49 return fmt.Errorf("unsupported Scan, storing driver.Value type %T into type *CustomTime", value)
50 }
51 return nil
52 }
53
54 func (ct CustomTime) Value() (driver.Value, error) {
55 return ct.Time, nil
56 }