my-log/tools/parse_date.go
Dan Jones 96c3b2ff30 Use ParseDate in Parse
Also limit to English, or we get lots of false positives
2024-02-25 13:12:13 -06:00

57 lines
1.2 KiB
Go

package tools
import (
"time"
dp "github.com/markusmobius/go-dateparser"
"github.com/markusmobius/go-dateparser/date"
)
const DateFormat = "January 02, 2006 at 03:04:05PM -0700"
// 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
}
conf := dp.Configuration{
CurrentTime: time.Now().Local(),
ReturnTimeAsPeriod: true,
Languages: []string{"en"},
}
d, err := dp.Parse(&conf, in)
t = d.Time
if err != nil {
d, err = dp.Parse(&conf, in, DateFormat)
t = d.Time
return
}
y, mon, day, h, loc := t.Year(), t.Month(), t.Day(), t.Hour(), t.Location()
switch d.Period {
case date.Second:
t = t.Truncate(time.Second)
case date.Minute:
t = t.Truncate(time.Minute)
case date.Hour:
t = time.Date(y, mon, day, h, 0, 0, 0, loc)
case date.Day:
t = time.Date(y, mon, day, 0, 0, 0, 0, loc)
case date.Month:
t = time.Date(y, mon, 1, 0, 0, 0, 0, loc)
case date.Year:
t = time.Date(y, 1, 1, 0, 0, 0, 0, loc)
}
return
}