Skip to content

Commit

Permalink
add IsZero to Time
Browse files Browse the repository at this point in the history
  • Loading branch information
guregu committed Aug 1, 2018
1 parent 1c57359 commit 80515d4
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
6 changes: 6 additions & 0 deletions time.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,9 @@ func (t Time) Ptr() *time.Time {
}
return &t.Time
}

// IsZero returns true for invalid Times, hopefully for future omitempty support.
// A non-null Time with a zero value will not be considered zero.
func (t Time) IsZero() bool {
return !t.Valid
}
17 changes: 17 additions & 0 deletions time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,23 @@ func TestTimeValueOrZero(t *testing.T) {
}
}

func TestTimeIsZero(t *testing.T) {
str := TimeFrom(timeValue)
if str.IsZero() {
t.Errorf("IsZero() should be false")
}

zero := TimeFrom(time.Time{})
if zero.IsZero() {
t.Errorf("IsZero() should be false")
}

null := TimeFromPtr(nil)
if !null.IsZero() {
t.Errorf("IsZero() should be true")
}
}

func assertTime(t *testing.T, ti Time, from string) {
if ti.Time != timeValue {
t.Errorf("bad %v time: %v ≠ %v\n", from, ti.Time, timeValue)
Expand Down
5 changes: 5 additions & 0 deletions zero/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,8 @@ func (t Time) Ptr() *time.Time {
}
return &t.Time
}

// IsZero returns true for null or zero Times, for potential future omitempty support.
func (t Time) IsZero() bool {
return !t.Valid || t.Time.IsZero()
}
17 changes: 17 additions & 0 deletions zero/time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,23 @@ func TestTimeValue(t *testing.T) {
}
}

func TestTimeIsZero(t *testing.T) {
str := TimeFrom(timeValue)
if str.IsZero() {
t.Errorf("IsZero() should be false")
}

zero := TimeFrom(time.Time{})
if !zero.IsZero() {
t.Errorf("IsZero() should be true")
}

null := TimeFromPtr(nil)
if !null.IsZero() {
t.Errorf("IsZero() should be true")
}
}

func assertTime(t *testing.T, ti Time, from string) {
if ti.Time != timeValue {
t.Errorf("bad %v time: %v ≠ %v\n", from, ti.Time, timeValue)
Expand Down

0 comments on commit 80515d4

Please sign in to comment.