Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the UTC time when I query mongodb in golang

Tags:

mongodb

go

mgo

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\n", item.SampleDate)

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

    err := collection.Find(bson.M{}).All(&items)
    if err == nil {
        fmt.Printf("%s\n", 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?

like image 246
jzapata Avatar asked Oct 28 '25 04:10

jzapata


1 Answers

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\n", 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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!