Skip to content

Commit f90bcfe

Browse files
committed
add Timeconstructor
1 parent 9bee77c commit f90bcfe

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

bson/constructor.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
"github.com/mongodb/mongo-go-driver/bson/decimal"
1616
"github.com/mongodb/mongo-go-driver/bson/elements"
1717
"github.com/mongodb/mongo-go-driver/bson/objectid"
18+
"time"
1819
)
1920

2021
// EC is a convenience variable provided for access to the ElementConstructor methods.
@@ -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: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212

1313
"github.com/mongodb/mongo-go-driver/bson/decimal"
1414
"github.com/stretchr/testify/require"
15+
"time"
1516
)
1617

1718
func requireElementsEqual(t *testing.T, expected *Element, actual *Element) {
@@ -271,6 +272,25 @@ 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+
actualTime := EC.Time("foo", time.Date(2018, 1, 1, 1, 1, 1, 1, time.UTC))
288+
actualDateTime := EC.DateTime("foo", 1514768461000)
289+
290+
requireElementsEqual(t, expected, actualTime)
291+
requireElementsEqual(t, expected, actualDateTime)
292+
})
293+
274294
t.Run("Null", func(t *testing.T) {
275295
buf := []byte{
276296
// type

0 commit comments

Comments
 (0)