background/utils/OrmTimeHook.go

52 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package utils
import (
"database/sql/driver"
"fmt"
"log"
"reflect"
"time"
)
type OrmTime struct {
time.Time
}
//重写 MarshaJSON 方法在此方法中实现自定义格式的转换程序中解析到JSON
func (t OrmTime) MarshalJSON() ([]byte, error) {
formatted := fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05"))
return []byte(formatted), nil
}
//JSON中解析到程序中
func (t *OrmTime) UnmarshalJSON(data []byte) (err error) {
log.Print(string(data))
now, err := time.ParseInLocation(`"2006-01-02 15:04:05"`, string(data), time.Local)
*t = OrmTime{Time: now}
return
}
//写入数据库时会调用该方法将自定义时间类型转换并写入数据库
func (t OrmTime) Value() (driver.Value, error) {
var zeroTime time.Time
if t.Time.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return t.Time, nil
}
//读取数据库时会调用该方法将时间数据转换成自定义时间类型
func (t *OrmTime) Scan(v interface{}) error {
typename := reflect.TypeOf(v).Kind().String()
x := reflect.Slice.String()
if typename == x {
tmp,ok := v.([]byte)
if ok{
ft,e := time.Parse("2006-01-02 15:04:05",string(tmp))
if nil != e{
return fmt.Errorf("can not convert %v to timestamp", v)
}
*t = OrmTime{Time:ft}
return nil
}
}
return fmt.Errorf("can not convert %v to timestamp", v)
}