Go语言中Gorm为何返回时间中间带个T了
如何处理Gorm返回时间字段中间带个T,直接上代码,copy到项目中就可以使用。不废话
上代码:time.go
package utils
import (
"fmt"
"time"
)
const (
LocalDateTimeFormat string = "2006-01-02 15:04:05"
)
type LocalTime time.Time
func (l *LocalTime) Scan(v interface{}) error {
value, ok := v.(time.Time)
if ok {
*l = LocalTime(value)
return nil
}
return fmt.Errorf("can not convert %v to timestamp", v)
}
func (l LocalTime) MarshalText() (text []byte, err error) {
b := make([]byte, 0, len(LocalDateTimeFormat))
//b = append(b, '"')
b = time.Time(l).AppendFormat(b, LocalDateTimeFormat)
//b = append(b, '"')
if string(b) == `0001-01-01 00:00:00` {
b = []byte(``)
}
return b, nil
}
具体使用
结果如下图:
如果是pgsql数据库,或者查询出来时间是cst等之类的格式的用下面的这个自定义类
cst_time.go
package utils
import (
"fmt"
"time"
)
const (
LocalDateTimeFormats string = "2006-01-02 15:04:05"
CSTDateTimeFormat string = "2006-01-02 15:04:05 -0700 CST"
)
type Cst_LocalTime time.Time
func (l *Cst_LocalTime) Scan(v interface{}) error {
value, ok := v.(time.Time)
if ok {
*l = Cst_LocalTime(value)
return nil
}
return fmt.Errorf("can not convert %v to timestamp", v)
}
func (l Cst_LocalTime) MarshalText() (text []byte, err error) {
b := make([]byte, 0, len(LocalDateTimeFormats))
b = time.Time(l).AppendFormat(b, LocalDateTimeFormats)
if string(b) == `0001-01-01 00:00:00` {
b = []byte{}
}
return b, nil
}
// 转换为正常格式的时间字符串(本地时区时间)
func (l Cst_LocalTime) String() string {
return time.Time(l).Format(LocalDateTimeFormats)
}
// NewLocalTimeFromCST 解析CST格式的时间字符串并创建LocalTime类型
func NewLocalTimeFromCST(cstTimeStr string) (Cst_LocalTime, error) {
t, err := time.Parse(CSTDateTimeFormat, cstTimeStr)
if err != nil {
return Cst_LocalTime{}, err
}
return Cst_LocalTime(t), nil
}