V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
aixinit
V2EX  ›  Go 编程语言

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

  •  
  •   aixinit · 2014-07-09 22:56:25 +08:00 · 1482 次点击
    这是一个创建于 3605 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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
    3 条回复    2014-07-10 08:51:03 +08:00
    siteshen
        1
    siteshen  
       2014-07-10 01:54:24 +08:00   ❤️ 1
    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
        2
    fx  
       2014-07-10 02:08:31 +08:00
    代码看起来真费劲
    aixinit
        3
    aixinit  
    OP
       2014-07-10 08:51:03 +08:00
    @siteshen 这个办法好!感谢!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3476 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 05:26 · PVG 13:26 · LAX 22:26 · JFK 01:26
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.