[GODRIVER-1135]  bson encode time.Time , decode is not time.Time format, Created: 13/Jun/19  Updated: 16/Nov/21  Resolved: 11/Jul/19

Status: Closed
Project: Go Driver
Component/s: BSON
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major - P3
Reporter: Tiansheng Ren Assignee: Emmanuel Eppinger (Inactive)
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

 bson encode time.Time format data,  decode is not time.Time format, but double type data.

 

test case:
 

	beforeTimeVal := time.Now()
	beforeTimeMap := map[string]interface{}{"ts": beforeTimeVal}
	before, err := Marshal(beforeTimeMap)
	noerr(t, err)
 
	afterTimeMap := map[string]interface{}{}
	err = Unmarshal(before, &afterTimeMap)
	noerr(t, err)
	afterTime, ok := afterTimeMap["ts"].(time.Time)
	if !ok {
		t.Errorf("after time format error. after time info:%#v", afterTimeMap)
		return
	}
	if afterTime.UnixNano() != beforeTimeVal.UnixNano() {
		t.Errorf("after time not equal before time. befere:%#v, after:%#v", beforeTimeVal, afterTime)
		return
	}

test case result:

/home/reage/go_src/src/mongodb/mongo-go-driver/bson/bson_test.go:67: after time format error. after time info:map[string]interface {}{"ts":1560433311128}
FAIL



 Comments   
Comment by Emmanuel Eppinger (Inactive) [ 11/Jul/19 ]

Hi reage,

 

If you would like to change the behavior of how time.Time is marshaled and unmarshalled you can create a custom registry and call RegisterTypeMapEntry on it with bson.dateTime and time.Time. See [registry.go|https://github.com/mongodb/mongo-go-driver/blob/master/bson/bsoncodec/registry.go].You can then have the marshalling/unmarshalling behavior you are looking for.

 

Thanks,

Emmanuel

Comment by Tiansheng Ren [ 13/Jun/19 ]

myself simple and violent implementation:
[github pull request|https://github.com/mongodb/mongo-go-driver/pull/164|

feature

  • bson decode 0x09 to time.Time

description:

  • reason:
    bson encode time.Time format data, decode is not time.Time format, but double type data.
  • achieve:

bson.Encode time.Time to primitive.DateTime. (data type flag:0x09)

bson.Decode data type flag 0x09 to time.Time

Generated at Thu Feb 08 08:35:45 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.