diff --git a/encode.go b/encode.go index afc35ed..2fa6a36 100644 --- a/encode.go +++ b/encode.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "math" + "time" ) // Encoder writes BSON values to an output stream. @@ -55,6 +56,11 @@ func (e *Encoder) marshal(v any) error { e.buf.Write([]byte(v)) e.buf.WriteByte(0) + case time.Time: + var b [8]byte + binary.LittleEndian.PutUint64(b[:], uint64(v.UnixMilli())) + e.buf.Write(b[:]) + case int32: var b [4]byte binary.LittleEndian.PutUint32(b[:], uint32(v)) diff --git a/encode_test.go b/encode_test.go index e0c2538..b979cb7 100644 --- a/encode_test.go +++ b/encode_test.go @@ -4,6 +4,7 @@ import ( "bytes" "math" "testing" + "time" ) func TestEncode(t *testing.T) { @@ -92,3 +93,27 @@ func TestEncodeNumbers(t *testing.T) { wantBytes(t, buf.Bytes(), "713d0ad7a3104540") buf.Reset() } + +func TestEncodeTime(t *testing.T) { + var err error + var buf bytes.Buffer + enc := NewEncoder(&buf) + + var ts time.Time + err = enc.Encode(ts) + mustOk(t, err) + wantBytes(t, buf.Bytes(), "0028d3ed7cc7ffff") + buf.Reset() + + ts = time.Unix(0, 0) + err = enc.Encode(ts) + mustOk(t, err) + wantBytes(t, buf.Bytes(), "0000000000000000") + buf.Reset() + + ts = time.Date(2023, 8, 17, 10, 20, 30, 0, time.UTC) + err = enc.Encode(ts) + mustOk(t, err) + wantBytes(t, buf.Bytes(), "b0cd02038a010000") + buf.Reset() +}