我對 Golang 和 MongoDB 比較陌生,遇到了一個日期問題,我似乎可以將 UTC 日期插入到 MongoDB 中,但是當我通過 Golang 查詢時,它會自動轉(zhuǎn)換為本地時間。我想在 UTC 中從 MongoDB 取回它而無需轉(zhuǎn)換。這是一個快速示例: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) }}我的輸出:2014-10-12 04:10:50.3992076 +0000 UTC2014-10-11 23:10:50.399 -0500 CDT看來 mgo 驅(qū)動程序可能會自動轉(zhuǎn)換它,因為當我從控制臺窗口查詢 mongodb 時,我的日期是 UTC。我是否在某處錯過了關(guān)閉此功能的 mgo 選項?
2 回答

有只小跳蛙
TA貢獻1824條經(jīng)驗 獲得超8個贊
Go time.Time值存儲時間和位置的瞬間。mgo BSON 解碼器將位置設(shè)置為time.Local。
您可以設(shè)置time.Local
為 UTC 位置:
time.Local = time.UTC
設(shè)計給第三方使用的包不應(yīng)該修改本地位置,但在應(yīng)用程序范圍內(nèi)是可以的。
所述Time.UTC()方法在時間作為接收器和所述位置設(shè)置為UTC在同一時刻返回的時間。此行將以 UTC 格式打印時間:
fmt.Printf("%s\n", items[0].SampleDate.UTC())
由于 MongoDB 存儲時間的精度低于 time.Time,因此從 MongoDB 返回的值可能不等于您存儲的值。
- 2 回答
- 0 關(guān)注
- 441 瀏覽
添加回答
舉報
0/150
提交
取消