dpmrakfbx820320638 2014-10-12 04:44
浏览 242
已采纳

在Golang中查询mongodb时如何获得UTC时间

I am relatively new to Golang and MongoDB and ran into a date issue where it appears that I can insert a UTC date into MongoDB, but when I query through Golang it is getting automatically converted to the local time. I want to get it back from MongoDB in UTC with no conversion. Here is a quick example:

type SampleItem struct {
    ObjId      bson.ObjectId `bson:"_id,omitempty" json:"-"`
    SampleDate time.Time     `bson:"sampleDate" json:"sampleDate"`
}

func TestMe() {

    var item SampleItem
    var items []SampleItem

    sess := getSession()
    defer sess.Close()

    item.SampleDate = time.Now().UTC()
    fmt.Printf("%s
", item.SampleDate)

    collection := sess.DB("myCollection").C("sampleItems")
    collection.Insert(item)

    err := collection.Find(bson.M{}).All(&items)
    if err == nil {
        fmt.Printf("%s
", items[0].SampleDate)
    }
}

My output:

2014-10-12 04:10:50.3992076 +0000 UTC

2014-10-11 23:10:50.399 -0500 CDT

It appears that the mgo driver may be automatically converting it because when I query mongodb from a console window my date is in UTC. Am I missing a mgo option somewhere that turns this off?

  • 写回答

2条回答 默认 最新

  • douqie1852 2014-10-12 04:56
    关注

    Go time.Time values store an instant in time and a location. The mgo BSON decoder sets the location to time.Local.

    You can set time.Local to the UTC location:

    time.Local = time.UTC
    

    A package designed to be used third parties should not modify the local location, but it's OK within the scope of an application.

    The Time.UTC() method returns a time at the same instant in time as the receiver and the location set to UTC. This line will print the time in UTC:

        fmt.Printf("%s
    ", items[0].SampleDate.UTC())
    

    Because MongoDB stores time with lower precision than a time.Time, the value returned from MongoDB may not equal the value you stored.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退