50 lines
1.3 KiB
Go
50 lines
1.3 KiB
Go
package utils
|
||
|
||
import (
|
||
"database/sql/driver"
|
||
"fmt"
|
||
"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) {
|
||
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)
|
||
}
|