my-log/tools/parse_date.go
Dan Jones 44e79916d3 🐛 Only truncate minutes and seconds
Also ensure we're getting date.Time for specific times
2024-02-25 09:53:52 -06:00

50 lines
1 KiB
Go

package tools
import (
"time"
dp "github.com/markusmobius/go-dateparser"
"github.com/markusmobius/go-dateparser/date"
)
// 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(&dp.Configuration{
CurrentTime: time.Now().Local(),
ReturnTimeAsPeriod: true,
}, in)
t = d.Time
if err != nil {
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
}