go时间字段格式化返回
时间字段的结构体使用 LocalTime 类型即可
package tool
import (
"database/sql/driver"
"fmt"
"goskeleton/app/global/variable"
"time"
)
type LocalTime struct {
time.Time
}
func (t LocalTime) MarshalJSON() ([]byte, error) {
d := t.Format(variable.DateFormat)
return []byte(`"` + d + `"`), nil
}
func (t LocalTime) Value() (driver.Value, error) {
var zeroTime time.Time
if t.Time.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return t.Time, nil
}
func (t *LocalTime) Scan(v interface{}) error {
value, ok := v.(time.Time)
if !ok {
switch v.(type) {
case int64:
value = time.Unix(v.(int64), 0)
default:
log.Println("时间戳格式不能解析", v)
return nil
}
}
*t = LocalTime{Time: value}
return nil
}
本文来自博客园,作者:Silent-Cxl,转载请注明原文链接:https://www.cnblogs.com/silent-cxl/p/15179950.html

浙公网安备 33010602011771号