beego 的orm 結(jié)構(gòu)體中時(shí)間如果用的是 time.Time 類似于下面這樣
Create_time time.Time `orm:"auto_now_add;type(datetime)" form:"-"`
Update_time time.Time `orm:"auto_now;type(datetime)"`
那么在前端渲染時(shí)拿到的數(shù)據(jù)就會(huì)是類似2014-07-07T23:58:28+08:00
這種玻蝌,顯然不是通常的顯示形式。如果想要拿到2014-07-07 23:58:28
這樣的形式該怎么辦呢?
經(jīng)過(guò)一同搜索之后,仍然沒發(fā)現(xiàn)什么好辦法能直接拿到想要的格式,我說(shuō)一下大家說(shuō)的最多的兩種方案。
一種是修改/usr/local/go/src/time/time.go
源碼(復(fù)制別人的代碼 沒有測(cè)試)
// MarshalJSON implements the json.Marshaler interface.
// The time is a quoted string in RFC 3339 format, with sub-second precision added if present.
func (t Time) MarshalJSON2() ([]byte, error) {
if y := t.Year(); y < 0 || y >= 10000 {
// RFC 3339 is clear that years are 4 digits exactly.
// See golang.org/issue/4556#c15 for more discussion.
return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
}
b := make([]byte, 0, len(RFC3339Nano)+2)
b = append(b, '"')
b = t.AppendFormat(b, RFC3339Nano)
b = append(b, '"')
return b, nil
}
func (t Time) MarshalJSON() ([]byte, error) {
if y := t.Year(); y < 0 || y >= 10000 {
// RFC 3339 is clear that years are 4 digits exactly.
// See golang.org/issue/4556#c15 for more discussion.
return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
}
b := make([]byte, 0, len("2006-01-02 15:04:05")+2)
b = append(b, '"')
b = t.AppendFormat(b, "2006-01-02 15:04:05")
b = append(b, '"')
return b, nil
}
第二種和第一種其實(shí)差不多 只不過(guò)是在你的結(jié)構(gòu)體中實(shí)現(xiàn) MarshalJSON
和UnmarshalJson
或者自定義一種類型重寫time
但是這兩種我都不太喜歡,所以我直接在模板中進(jìn)行格式化
{{.Create_time.Format "2006-01-02 15:04:05"}}
參考文章:
https://github.com/astaxie/beego/issues/686
https://studygolang.com/articles/11685
https://blog.csdn.net/wo541075754/article/details/79513484
http://www.reibang.com/p/5250ef0954b7