diff --git a/bson/constructor.go b/bson/constructor.go index 8932ac460d..be4e682d03 100644 --- a/bson/constructor.go +++ b/bson/constructor.go @@ -634,6 +634,11 @@ func (ValueConstructor) DateTime(dt int64) *Value { return EC.DateTime("", dt).value } +// Time creates a datetime value from the argument. +func (ValueConstructor) Time(t time.Time) *Value { + return EC.Time("", t).value +} + // Null creates a null value from the argument. func (ValueConstructor) Null() *Value { return EC.Null("").value diff --git a/bson/constructor_test.go b/bson/constructor_test.go index 41d18b9d47..1c88f3b502 100644 --- a/bson/constructor_test.go +++ b/bson/constructor_test.go @@ -731,6 +731,26 @@ func TestConstructor(t *testing.T) { requireValuesEqual(t, expected, actual) }) + t.Run("time", func(t *testing.T) { + buf := []byte{ + // type + 0x9, + // key + 0x0, + // value + 0xC9, 0x6C, 0x3C, 0xAF, 0x60, 0x1, 0x0, 0x0, + } + + expected := &Value{start: 0, offset: 2, data: buf, d: nil} + + date := time.Date(2018, 1, 1, 1, 1, 1, int(1*time.Millisecond), time.UTC) + actualTime := VC.Time(date) + actualDateTime := VC.DateTime(date.UnixNano() / 1e6) + + requireValuesEqual(t, expected, actualTime) + requireValuesEqual(t, expected, actualDateTime) + }) + t.Run("Null", func(t *testing.T) { buf := []byte{ // type