You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
937 B
Go

package model
import (
"database/sql/driver"
"fmt"
"strings"
"time"
)
type MyTime struct {
time.Time
}
func (t *MyTime) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
return nil
}
var err error
//前端接收的时间字符串
str := string(data)
//去除接收的str收尾多余的"
timeStr := strings.Trim(str, "\"")
tt, err := time.Parse("2006-01-02 15:04:05", timeStr)
*t = MyTime{tt}
return err
}
func (t MyTime) MarshalJSON() ([]byte, error) {
formatted := fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05"))
return []byte(formatted), nil
}
func (t MyTime) Value() (driver.Value, error) {
var zeroTime time.Time
if t.Time.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return t.Time, nil
}
func (t *MyTime) Scan(v interface{}) error {
value, ok := v.(time.Time)
if ok {
*t = MyTime{Time: value}
return nil
}
return fmt.Errorf("can not convert %v to timestamp", v)
}