Skip to content

Commit d40cbfc

Browse files
authored
Merge pull request #105 from bg451/add_date_time_is_zero
Adds IsZero functionality to DateTime
2 parents a239ff1 + 397e96b commit d40cbfc

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

time.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ import (
2929
"go.mongodb.org/mongo-driver/bson/bsontype"
3030
)
3131

32+
var (
33+
// UnixZero sets the zero unix timestamp we want to compare against.
34+
// Unix 0 for an EST timezone is not equivalent to a UTC timezone.
35+
UnixZero = time.Unix(0, 0).UTC()
36+
)
37+
3238
func init() {
3339
dt := DateTime{}
3440
Default.Add("datetime", &dt, IsDateTime)
@@ -123,6 +129,16 @@ func (t DateTime) String() string {
123129
return NormalizeTimeForMarshal(time.Time(t)).Format(MarshalFormat)
124130
}
125131

132+
// IsZero returns whether the date time is a zero value
133+
func (t DateTime) IsZero() bool {
134+
return time.Time(t).IsZero()
135+
}
136+
137+
// IsUnixZerom returns whether the date time is equivalent to time.Unix(0, 0).UTC().
138+
func (t DateTime) IsUnixZero() bool {
139+
return time.Time(t) == UnixZero
140+
}
141+
126142
// MarshalText implements the text marshaller interface
127143
func (t DateTime) MarshalText() ([]byte, error) {
128144
return []byte(t.String()), nil

time_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,27 @@ func TestNewDateTime(t *testing.T) {
5353
assert.EqualValues(t, time.Unix(0, 0).UTC(), NewDateTime())
5454
}
5555

56+
func TestIsZero(t *testing.T) {
57+
var empty DateTime
58+
assert.True(t, empty.IsZero())
59+
assert.False(t, DateTime(time.Unix(100, 5)).IsZero())
60+
61+
// time.Unix(0,0) does not produce a true zero value struct,
62+
// so this is expected to fail.
63+
assert.False(t, NewDateTime().IsZero())
64+
}
65+
66+
func TestIsUnixZero(t *testing.T) {
67+
dt := NewDateTime()
68+
assert.True(t, dt.IsUnixZero())
69+
assert.NotEqual(t, dt.IsZero(), dt.IsUnixZero())
70+
// Test configuring UnixZero
71+
estLocation := time.FixedZone("EST", int((-5 * time.Hour).Seconds()))
72+
estUnixZero := time.Unix(0, 0).In(estLocation)
73+
UnixZero = estUnixZero
74+
assert.True(t, DateTime(estUnixZero).IsUnixZero())
75+
}
76+
5677
func TestParseDateTime_errorCases(t *testing.T) {
5778
_, err := ParseDateTime("yada")
5879
assert.Error(t, err)

0 commit comments

Comments
 (0)