Skip to content

Commit

Permalink
feat: add date functions Before, After and Compare
Browse files Browse the repository at this point in the history
  • Loading branch information
francesconi committed Oct 29, 2024
1 parent 2d62b32 commit 26017b2
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
24 changes: 24 additions & 0 deletions timex/date.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,30 @@ func ParseDate(s string) (Date, error) {
return NewDateFromTime(t), nil
}

func (d Date) Before(d2 Date) bool {
if d.Year != d2.Year {
return d.Year < d2.Year
}
if d.Month != d2.Month {
return d.Month < d2.Month
}
return d.Day < d2.Day
}

func (d Date) After(d2 Date) bool {
return d2.Before(d)
}

func (d Date) Compare(d2 Date) int {
if d.Before(d2) {
return -1
}
if d.After(d2) {
return +1
}
return 0
}

func (d Date) String() string {
return fmt.Sprintf("%04d-%02d-%02d", d.Year, d.Month, d.Day)
}
Expand Down
48 changes: 48 additions & 0 deletions timex/date_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,54 @@ func TestParseDate(t *testing.T) {
}
}
}

func TestDateBefore(t *testing.T) {
tests := []struct {
d1, d2 Date
want bool
}{
{Date{1962, 12, 31}, Date{1963, 1, 1}, true},
{Date{1962, 1, 1}, Date{1962, 2, 1}, true},
{Date{1962, 1, 1}, Date{1962, 1, 1}, false},
{Date{1962, 12, 30}, Date{1962, 12, 31}, true},
}

for _, tt := range tests {
assert.Equal(t, tt.want, tt.d1.Before(tt.d2))
}
}

func TestDateAfter(t *testing.T) {
tests := []struct {
d1, d2 Date
want bool
}{
{Date{1962, 12, 31}, Date{1963, 1, 1}, false},
{Date{1962, 1, 1}, Date{1962, 2, 1}, false},
{Date{1962, 1, 1}, Date{1962, 1, 1}, false},
{Date{1962, 12, 30}, Date{1962, 12, 31}, false},
}

for _, tt := range tests {
assert.Equal(t, tt.want, tt.d1.After(tt.d2))
}
}

func TestDateCompare(t *testing.T) {
tests := []struct {
d1, d2 Date
want int
}{
{Date{1962, 12, 31}, Date{1963, 1, 1}, -1},
{Date{1962, 1, 1}, Date{1962, 1, 1}, 0},
{Date{1962, 12, 31}, Date{1962, 12, 30}, +1},
}

for _, tt := range tests {
assert.Equal(t, tt.want, tt.d1.Compare(tt.d2))
}
}

func TestMarshalJSON(t *testing.T) {
got, err := json.Marshal(Date{2023, 5, 4})
assert.Nil(t, err)
Expand Down

0 comments on commit 26017b2

Please sign in to comment.