From b946ab8c0f4455efd7423b52f4b383aec28d01b6 Mon Sep 17 00:00:00 2001 From: Mohamad Harith Date: Sun, 27 Feb 2022 14:07:24 +0800 Subject: [PATCH] feat: before and after methods for Time --- civil/civil.go | 20 ++++++++++++++++++++ civil/civil_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/civil/civil.go b/civil/civil.go index a39246802af..6e549f118ae 100644 --- a/civil/civil.go +++ b/civil/civil.go @@ -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) { diff --git a/civil/civil_test.go b/civil/civil_test.go index 18711de2832..b7b8b885995 100644 --- a/civil/civil_test.go +++ b/civil/civil_test.go @@ -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