✨ Add tools.ParseDate
This commit is contained in:
parent
c01fb53a0e
commit
70b82761c2
8 changed files with 1067 additions and 8 deletions
45
tools/parse_date.go
Normal file
45
tools/parse_date.go
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
package tools
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
dp "github.com/markusmobius/go-dateparser"
|
||||
"github.com/markusmobius/go-dateparser/date"
|
||||
)
|
||||
|
||||
const (
|
||||
day = time.Hour * 24
|
||||
)
|
||||
|
||||
// These are somewhat arbitrary, but reasonably useful min and max times
|
||||
var (
|
||||
MinTime = time.Unix(-2208988800, 0) // Jan 1, 1900
|
||||
MaxTime = MinTime.Add(1<<63 - 1)
|
||||
)
|
||||
|
||||
func ParseDate(in string) (t time.Time, err error) {
|
||||
if in == "min" {
|
||||
return MinTime, nil
|
||||
}
|
||||
if in == "max" {
|
||||
return MaxTime, nil
|
||||
}
|
||||
|
||||
d, err := dp.Parse(nil, in)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
t = d.Time.Local()
|
||||
trunc := time.Second
|
||||
switch d.Period {
|
||||
case date.Minute:
|
||||
trunc = time.Minute
|
||||
case date.Hour:
|
||||
trunc = time.Hour
|
||||
case date.Day:
|
||||
trunc = day
|
||||
// @todo Handle other cases separately
|
||||
}
|
||||
t = t.Truncate(trunc)
|
||||
return
|
||||
}
|
||||
51
tools/parse_date_test.go
Normal file
51
tools/parse_date_test.go
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
package tools
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParseDate(t *testing.T) {
|
||||
now := time.Now().Local()
|
||||
sec := now.Truncate(time.Second)
|
||||
today := now.Truncate(day)
|
||||
tomorrow := today.Add(day)
|
||||
yesterday := today.Add(-day)
|
||||
twoMin := now.Add(2 * time.Minute).Truncate(time.Minute)
|
||||
twoHour := now.Add(2 * time.Hour).Truncate(time.Hour)
|
||||
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, ""},
|
||||
{"min", MinTime, ""},
|
||||
{"max", MaxTime, ""},
|
||||
{"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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue