Skip to content

Commit c6cbbd6

Browse files
committed
Merge branch 'master' of https://github.com/Hixon10/mongo-go-driver into master
Change-Id: Iadec329fcdcc8443cd935c2bd5fc896ea7ad3931
2 parents 6b08246 + 9af5d0f commit c6cbbd6

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

bson/constructor.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"fmt"
1212
"math"
1313
"reflect"
14+
"time"
1415

1516
"github.com/mongodb/mongo-go-driver/bson/decimal"
1617
"github.com/mongodb/mongo-go-driver/bson/elements"
@@ -325,6 +326,7 @@ func (ElementConstructor) Boolean(key string, b bool) *Element {
325326
}
326327

327328
// DateTime creates a datetime element with the given key and value.
329+
// dt represents milliseconds since the Unix epoch
328330
func (ElementConstructor) DateTime(key string, dt int64) *Element {
329331
size := uint32(1 + len(key) + 1 + 8)
330332
elem := newElement(0, 1+uint32(len(key))+1)
@@ -338,6 +340,11 @@ func (ElementConstructor) DateTime(key string, dt int64) *Element {
338340
return elem
339341
}
340342

343+
// Time creates a datetime element with the given key and value.
344+
func (c ElementConstructor) Time(key string, time time.Time) *Element {
345+
return c.DateTime(key, time.Unix()*1000)
346+
}
347+
341348
// Null creates a null element with the given key.
342349
func (ElementConstructor) Null(key string) *Element {
343350
size := uint32(1 + len(key) + 1)

bson/constructor_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ package bson
99
import (
1010
"bytes"
1111
"testing"
12+
"time"
1213

1314
"github.com/mongodb/mongo-go-driver/bson/decimal"
1415
"github.com/stretchr/testify/require"
@@ -271,6 +272,26 @@ func TestConstructor(t *testing.T) {
271272
requireElementsEqual(t, expected, actual)
272273
})
273274

275+
t.Run("time", func(t *testing.T) {
276+
buf := []byte{
277+
// type
278+
0x9,
279+
// key
280+
0x66, 0x6f, 0x6f, 0x0,
281+
// value
282+
0xC8, 0x6C, 0x3C, 0xAF, 0x60, 0x1, 0x0, 0x0,
283+
}
284+
285+
expected := &Element{&Value{start: 0, offset: 5, data: buf, d: nil}}
286+
287+
date := time.Date(2018, 1, 1, 1, 1, 1, 1, time.UTC)
288+
actualTime := EC.Time("foo", date)
289+
actualDateTime := EC.DateTime("foo", date.Unix()*1000)
290+
291+
requireElementsEqual(t, expected, actualTime)
292+
requireElementsEqual(t, expected, actualDateTime)
293+
})
294+
274295
t.Run("Null", func(t *testing.T) {
275296
buf := []byte{
276297
// type

0 commit comments

Comments
 (0)