Date format Handling from JSON to BSON using GO

@Shankar_Nagarajan Here’s the above example adapted for Go Driver v2:

type MyDate time.Time

type MyData struct {
	FieldS string
	FieldI int64
	FieldD *MyDate
}

func (v MyDate) MarshalBSONValue() (byte, []byte, error) {
	typ, data, err := bson.MarshalValue(time.Time(v))
	return byte(typ), data, err
}

func (v *MyDate) UnmarshalBSONValue(typ byte, data []byte) error {
	var res time.Time
	if err := bson.UnmarshalValue(bson.Type(typ), data, &res); err != nil {
		return err
	}
	*v = MyDate(res)

	return nil
}

See the full example in the Go Playground here.

Note that the signature of UnmarshalBSONValue and MarshalBSONValue in Go Driver v2 use byte instead of bsontype.Type, but are otherwise the same.

1 Like