go 时间转换问题,请各位大神指点

2014-07-09 22:56:25 +08:00
 aixinit
beego 中时间的问题,

type Portal_user struct{
Id int
User_code string orm:"pk"
Opdate time.Time
Updatedat time.Time orm:"auto_now_add;type(datetime)"

}
var pulist []*Portal_user
o := orm.NewOrm()
o.QueryTable("portal_user").All(&pulist)

能否从Portal_user 的struct 上设置时间格式呢?
this.ServeJson() 转换时间结果默认是{"Updatedat":"2014-07-07T23:58:28+08:00"}
我想要orm 自动 转换结果为{"Updatedat":"2014-07-07 23:58:28"} 这样能否实现呢?

另外
x:=time.Now().Format("2006-01-02 15:04:05")
s,_:= time.ParseInLocation("2006-01-02 15:04:05",x,time.Local)
fmt.Println(s)
通过对时间的转换,得到的时间总是带+0000 UTC 这样的,怎么转换为不带这个时间?
2014-07-09 22:49:25 +0000 UTC
1504 次点击
所在节点    Go 编程语言
3 条回复
siteshen
2014-07-10 01:54:24 +08:00
1. 不能。不过可以自定义一个struct,自己实现json.Marshaler这个接口。
type SimpleTime time.Time
func (SimpleTime t) MarshalJSON() ([]byte, error) {
// do whatever you want
}

type Portal_user struct {
Opdate SimpleTime
}

2. http://godoc.org/time#Time 文档有说明,Each Time has associated with it a Location 所以是没法去掉Location的,但统一转成UTC时间后,就可以认为是没有Location信息了;如果只是要打印,自己定义类型,然后实现Stringer接口即可。
fx
2014-07-10 02:08:31 +08:00
代码看起来真费劲
aixinit
2014-07-10 08:51:03 +08:00
@siteshen 这个办法好!感谢!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/121846

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX