Skip to content

Commit

Permalink
feat(civil): add Before and After methods to civil.Time (#5703)
Browse files Browse the repository at this point in the history
  • Loading branch information
mohamadHarith authored May 24, 2022
1 parent 7d99944 commit 7acaaaf
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
20 changes: 20 additions & 0 deletions civil/civil.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,26 @@ func (t Time) IsZero() bool {
return (t.Hour == 0) && (t.Minute == 0) && (t.Second == 0) && (t.Nanosecond == 0)
}

// Before reports whether t1 occurs before t2.
func (t1 Time) Before(t2 Time) bool {
if t1.Hour != t2.Hour {
return t1.Hour < t2.Hour
}
if t1.Minute != t2.Minute {
return t1.Minute < t2.Minute
}
if t1.Second != t2.Second {
return t1.Second < t2.Second
}

return t1.Nanosecond < t2.Nanosecond
}

// After reports whether t1 occurs after t2.
func (t1 Time) After(t2 Time) bool {
return t2.Before(t1)
}

// MarshalText implements the encoding.TextMarshaler interface.
// The output is the result of t.String().
func (t Time) MarshalText() ([]byte, error) {
Expand Down
32 changes: 32 additions & 0 deletions civil/civil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,38 @@ func TestTimeIsZero(t *testing.T) {
}
}

func TestTimeBefore(t *testing.T) {
for _, test := range []struct {
t1, t2 Time
want bool
}{
{Time{12, 0, 0, 0}, Time{14, 0, 0, 0}, true},
{Time{12, 20, 0, 0}, Time{12, 30, 0, 0}, true},
{Time{12, 20, 10, 0}, Time{12, 20, 20, 0}, true},
{Time{12, 20, 10, 5}, Time{12, 20, 10, 10}, true},
} {
if got := test.t1.Before(test.t2); got != test.want {
t.Errorf("%v.Before(%v): got %t, want %t", test.t1, test.t2, got, test.want)
}
}
}

func TestTimeAfter(t *testing.T) {
for _, test := range []struct {
t1, t2 Time
want bool
}{
{Time{12, 0, 0, 0}, Time{14, 0, 0, 0}, false},
{Time{12, 20, 0, 0}, Time{12, 30, 0, 0}, false},
{Time{12, 20, 10, 0}, Time{12, 20, 20, 0}, false},
{Time{12, 20, 10, 5}, Time{12, 20, 10, 10}, false},
} {
if got := test.t1.After(test.t2); got != test.want {
t.Errorf("%v.Before(%v): got %t, want %t", test.t1, test.t2, got, test.want)
}
}
}

func TestDateTimeToString(t *testing.T) {
for _, test := range []struct {
str string
Expand Down

0 comments on commit 7acaaaf

Please sign in to comment.