为了实现gin API接口返回的时间格式符合andriod等的习惯,方便解析,需要对Time的json解析进行重写,由于牵涉到了gorm的数据类型,所以只能简化操作在获取到数据object或转换成自定义格式,代码如下
package jsonTime
import (
"database/sql/driver"
"fmt"
"time"
)
//重写MarshalJSON实现models json返回的时间格式
type JSONTime struct {
time.Time
}
const (
timeFormart = "2006-01-02 15:04:05"
)
//type JSONTime time.Time
func (t JSONTime) Now() JSONTime {
t = JSONTime{time.Now()}
return t
}
func (t JSONTime) MarshalJSON() ([]byte, error) {
formatted := fmt.Sprintf("\"%s\"", t.Format(timeFormart))
return []byte(formatted), nil
}
func (t JSONTime) Value() (driver.Value, error) {
var zeroTime time.Time
if t.Time.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return t.Time, nil
}
func (t *JSONTime) Scan(v interface{}) error {
value, ok := v.(time.Time)
if ok {
*t = JSONTime{Time: value}
return nil
}
return fmt.Errorf("无法转换 %v 的时间格式", v)
}
// type Time time.Time
func (t *JSONTime) UnmarshalJSON(data []byte) (err error) {
now, err := time.ParseInLocation(`"`+timeFormart+`"`, string(data), time.Local)
*t = JSONTime{now}
return
}
另外也可以使用强大的go版的carbon https://github.com/golang-module/carbon