2021-01-12 15:39:31 +00:00
|
|
|
|
package utils
|
2021-02-05 17:46:59 +00:00
|
|
|
|
|
2021-01-12 15:39:31 +00:00
|
|
|
|
import (
|
|
|
|
|
"database/sql/driver"
|
2021-02-05 17:46:59 +00:00
|
|
|
|
"fmt"
|
2021-02-10 15:57:22 +00:00
|
|
|
|
"log"
|
2021-01-12 15:39:31 +00:00
|
|
|
|
"reflect"
|
2021-02-05 17:46:59 +00:00
|
|
|
|
"time"
|
2021-01-12 15:39:31 +00:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
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) {
|
2021-02-10 15:57:22 +00:00
|
|
|
|
log.Print(string(data))
|
|
|
|
|
now, err := time.ParseInLocation(`"2006-01-02 15:04:05"`, string(data), time.Local)
|
2021-01-12 15:39:31 +00:00
|
|
|
|
*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)
|
|
|
|
|
}
|