MGO time.Time with Location is automatically converted to UTC?

900 views
Skip to first unread message

al...@deefuse.com

unread,
Nov 26, 2015, 2:13:06 PM11/26/15
to mgo-users
Hi,

This is more of a confirmation rather than a question: a time.Time with a time.Location attached to it, when inserted into MongoDB gets "automagically" converted to the UTC time?

For example:

type Test struct {    
   
Date time.Time    
}


func main
() {
   
var err error    
   
    loc
, err := time.LoadLocation("Europe/Bucharest")    
   
if err != nil {    
        log
.Fatal(err)    
   
}    
    lay
:= "2006 Jan _2 15:04:05"    
    val
:= "2015 Nov 26 19:00:00"


    t1
, err := time.Parse(lay, val)    
   
if err != nil {    
        log
.Fatal(err)    
   
}    
    fmt
.Printf("t1: %+v\n", t1)    
    fmt
.Printf("u2: %+v\n", t1.UTC())    
    fmt
.Printf("s1: %+v\n", t1.Unix())    
    fmt
.Println("")    
   
    t2
, err := time.ParseInLocation(lay, val, loc)    
   
if err != nil {    
        log
.Fatal(err)
   
}
    fmt
.Printf("t2: %+v\n", t2)
    fmt
.Printf("u2: %+v\n", t2.UTC())
    fmt
.Printf("s2: %+v\n", t2.Unix())
    fmt
.Println("")


    s
, _ := mgo.Dial("...")
    coll
:= s.DB("...").C("test")


    err
= coll.Insert(&Test{
       
Date: t1,
   
})


    err
= coll.Insert(&Test{
       
Date: t2,
   
})


   
var res []Test
    err
= coll.Find(bson.M{}).All(&res)
    fmt
.Printf("%+v\n", res)


}

Go output:

t1: 2015-11-26 19:00:00 +0000 UTC
u2
: 2015-11-26 19:00:00 +0000 UTC
s1
: 1448564400


t2
: 2015-11-26 19:00:00 +0200 EET
u2
: 2015-11-26 17:00:00 +0000 UTC
s2
: 1448557200


[{Date:2015-11-26 19:00:00 +0000 UTC} {Date:2015-11-26 17:00:00 +0000 UTC}]



Inside MongoDB you'll have the following:

> db.test.find().pretty();
{
       
"_id" : ObjectId("56575627ef8a3999e44422fa"),
       
"date" : ISODate("2015-11-26T19:00:00Z")
}
{
       
"_id" : ObjectId("56575627ef8a3999e44422fb"),
       
"date" : ISODate("2015-11-26T17:00:00Z")
}

Is this a feature or am I doing something wrong here?

Thanks,
Alex.

Gustavo Niemeyer

unread,
Nov 26, 2015, 4:05:22 PM11/26/15
to mgo-...@googlegroups.com
Hi Alex,

I wouldn't quite call it a feature, but more like the expected behavior. MongoDB timestamps do not carry a timezone, so mgo handles them as UTC when going back and forth.

--
You received this message because you are subscribed to the Google Groups "mgo-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mgo-users+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--

al...@deefuse.com

unread,
Nov 26, 2015, 6:23:36 PM11/26/15
to mgo-users
Hi and thanks for clearing that out for me.

I had a quick look at the code to see where the conversion happens. Am i right in saying that this is done in "bson/encode.go" lines 431 - 434?

Thanks,
Alex

Reply all
Reply to author
Forward
0 new messages