package tools import ( "fmt" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const day = time.Hour * 24 func TestParseDate(t *testing.T) { now := time.Now().Local() y, mon, d, h, loc := now.Year(), now.Month(), now.Day(), now.Hour(), now.Location() sec := now.Truncate(time.Second) today := time.Date(y, mon, d, 0, 0, 0, 0, loc) tomorrow := time.Date(y, mon, d+1, 0, 0, 0, 0, loc) yesterday := time.Date(y, mon, d-1, 0, 0, 0, 0, loc) twoMin := now.Add(2 * time.Minute).Truncate(time.Minute) twoHour := time.Date(y, mon, d, h+2, 0, 0, 0, loc) firstMonth := time.Date(y, mon, 1, 0, 0, 0, 0, loc) firstYear := time.Date(y, 1, 1, 0, 0, 0, 0, loc) exact := "2075-02-12T12:13:54.536-02:00" exactd, _ := time.ParseInLocation(time.RFC3339, exact, nil) var ts int64 = 1708876012 tsd := time.Unix(ts, 0) ent := "February 25, 2024 at 04:00:13AM +0230" entd, _ := time.Parse(DateFormat, ent) tests := []struct { name string exp time.Time err string }{ {"now", sec, ""}, {"today", today, ""}, {"tomorrow", tomorrow, ""}, {"yesterday", yesterday, ""}, {"in two minutes", twoMin, ""}, {"in two hours", twoHour, ""}, {"this month", firstMonth, ""}, {"this year", firstYear, ""}, {"min", MinTime, ""}, {"max", MaxTime, ""}, {exact, exactd, ""}, {fmt.Sprint(ts), tsd, ""}, {ent, entd, ""}, {"not a date", now, fmt.Sprintf(`failed to parse "%s": unknown format`, "not a date")}, } for _, tt := range tests { t.Run(tt.name, getDateTest(tt.name, tt.exp, tt.err)) } } func getDateTest(in string, exp time.Time, err string) func(t *testing.T) { return func(t *testing.T) { out, er := ParseDate(in) if err != "" { assert.ErrorContains(t, er, err) } else { require.NoError(t, er) assert.Equal(t, exp, out) } } }