Skip to content

Commit

Permalink
Merge pull request #105 from bg451/add_date_time_is_zero
Browse files Browse the repository at this point in the history
Adds IsZero functionality to DateTime
  • Loading branch information
casualjim committed Mar 16, 2023
2 parents a239ff1 + 397e96b commit d40cbfc
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
16 changes: 16 additions & 0 deletions time.go
Expand Up @@ -29,6 +29,12 @@ import (
"go.mongodb.org/mongo-driver/bson/bsontype"
)

var (
// UnixZero sets the zero unix timestamp we want to compare against.
// Unix 0 for an EST timezone is not equivalent to a UTC timezone.
UnixZero = time.Unix(0, 0).UTC()
)

func init() {
dt := DateTime{}
Default.Add("datetime", &dt, IsDateTime)
Expand Down Expand Up @@ -123,6 +129,16 @@ func (t DateTime) String() string {
return NormalizeTimeForMarshal(time.Time(t)).Format(MarshalFormat)
}

// IsZero returns whether the date time is a zero value
func (t DateTime) IsZero() bool {
return time.Time(t).IsZero()
}

// IsUnixZerom returns whether the date time is equivalent to time.Unix(0, 0).UTC().
func (t DateTime) IsUnixZero() bool {
return time.Time(t) == UnixZero
}

// MarshalText implements the text marshaller interface
func (t DateTime) MarshalText() ([]byte, error) {
return []byte(t.String()), nil
Expand Down
21 changes: 21 additions & 0 deletions time_test.go
Expand Up @@ -53,6 +53,27 @@ func TestNewDateTime(t *testing.T) {
assert.EqualValues(t, time.Unix(0, 0).UTC(), NewDateTime())
}

func TestIsZero(t *testing.T) {
var empty DateTime
assert.True(t, empty.IsZero())
assert.False(t, DateTime(time.Unix(100, 5)).IsZero())

// time.Unix(0,0) does not produce a true zero value struct,
// so this is expected to fail.
assert.False(t, NewDateTime().IsZero())
}

func TestIsUnixZero(t *testing.T) {
dt := NewDateTime()
assert.True(t, dt.IsUnixZero())
assert.NotEqual(t, dt.IsZero(), dt.IsUnixZero())
// Test configuring UnixZero
estLocation := time.FixedZone("EST", int((-5 * time.Hour).Seconds()))
estUnixZero := time.Unix(0, 0).In(estLocation)
UnixZero = estUnixZero
assert.True(t, DateTime(estUnixZero).IsUnixZero())
}

func TestParseDateTime_errorCases(t *testing.T) {
_, err := ParseDateTime("yada")
assert.Error(t, err)
Expand Down

0 comments on commit d40cbfc

Please sign in to comment.