自定义类型
type DateTime time.Time
func (d DateTime) MarshalJSON() ([]byte, error) {
t := time.Time(d)
if t.IsZero() {
return []byte{'"', '"'}, nil
}
res := make([]byte, 0, len(timeFormat)+2)
res = append(res, '"')
res = t.AppendFormat(res, timeFormat)
res = append(res, '"')
return res, nil
}
func (d *DateTime) UnmarshalJSON(bytes []byte) error {
timeStr := strings.Trim(string(bytes), `"`)
dateTime, err := time.ParseInLocation(timeFormat, timeStr, time.Local)
*d = DateTime(dateTime)
return err
}
func (d *DateTime) FromDB(bytes []byte) error {
dateTime, err := time.ParseInLocation(time.RFC3339Nano, string(bytes), time.Local)
*d = DateTime(dateTime)
return err
}
func (d DateTime) ToDB() ([]byte, error) {
res := make([]byte, 0, len(timeFormat))
return time.Time(d).AppendFormat(res, timeFormat), nil
}
type NullTime sql.NullTime
func (s NullTime) MarshalJSON() ([]byte, error) {
if !s.Valid {
return []byte("null"), nil
}
return []byte(`"` + s.StringValue("2006-01-02 15:04:05") + `"`), nil
}
func (s *NullTime) UnmarshalJSON(data []byte) error {
t := sql.NullTime{}
if err := json.Unmarshal(data, &t); err != nil {
timeStr := strings.Trim(string(data), `"`)
if len(timeStr) >= 20 {
timeStr = timeStr[:10] + " " + timeStr[11:19]
}
if len(timeStr) < 11 {
timeStr += " 00:00:00"
}
timeVal, err := time.Parse("2006-01-02 15:04:05", timeStr)
if err != nil {
return err
}
*s = NullTime{Time: val, Valid: true}
return nil
}
*s = NullTime(t)
return nil
}
func (s NullTime) String() string {
return s.StringValue("2006-01-02 15:04:05")
}
// 读取数据库
func (s *NullTime) Scan(value interface{}) error {
n := sql.NullTime{Time: s.Time}
if err := n.Scan(value); err != nil {
return err
}
*s = NullTime(n)
return nil
}
// 写入数据库
func (s NullTime) Value() (driver.Value, error) {
if !s.Valid {
return nil, nil
}
return s.StringValue("2006-01-02 15:04:05"), nil
}
func (s NullTime) StringValue(layout string) string {
return s.Time.Format(layout)
}