72 lines
1.3 KiB
Go
72 lines
1.3 KiB
Go
package schemas
|
|
|
|
import (
|
|
"database/sql/driver"
|
|
"encoding/json"
|
|
"time"
|
|
)
|
|
|
|
type CustomTime struct {
|
|
Time *time.Time
|
|
}
|
|
|
|
// MarshalJSON 实现 JSON 序列化
|
|
func (ct CustomTime) MarshalJSON() ([]byte, error) {
|
|
if ct.Time == nil {
|
|
return []byte(`""`), nil
|
|
}
|
|
return json.Marshal(ct.Time.Format("2006-01-02 15:04:05"))
|
|
}
|
|
|
|
// UnmarshalJSON 实现 JSON 反序列化
|
|
func (ct *CustomTime) UnmarshalJSON(data []byte) error {
|
|
var timeStr string
|
|
if err := json.Unmarshal(data, &timeStr); err != nil {
|
|
return err
|
|
}
|
|
|
|
if timeStr == "" {
|
|
ct.Time = nil
|
|
return nil
|
|
}
|
|
|
|
parsedTime, err := time.Parse("2006-01-02 15:04:05", timeStr)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
ct.Time = &parsedTime
|
|
return nil
|
|
}
|
|
|
|
// Scan 实现 sql.Scanner 接口,用于数据库扫描
|
|
func (ct *CustomTime) Scan(value interface{}) error {
|
|
if value == nil {
|
|
ct.Time = nil
|
|
return nil
|
|
}
|
|
|
|
switch v := value.(type) {
|
|
case time.Time:
|
|
ct.Time = &v
|
|
case *time.Time:
|
|
ct.Time = v
|
|
default:
|
|
ct.Time = nil
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Value 实现 driver.Valuer 接口,用于数据库存储
|
|
func (ct CustomTime) Value() (driver.Value, error) {
|
|
if ct.Time == nil {
|
|
return nil, nil
|
|
}
|
|
return *ct.Time, nil
|
|
}
|
|
|
|
// NewCustomTime 创建新的 CustomTime 实例
|
|
func NewCustomTime(t *time.Time) CustomTime {
|
|
return CustomTime{Time: t}
|
|
}
|