2020-12-27 17:09:45 +00:00
|
|
|
package date
|
|
|
|
|
2021-05-11 19:53:19 +00:00
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
2022-10-12 16:56:22 +00:00
|
|
|
naturaldate "github.com/tj/go-naturaldate"
|
2021-05-11 19:53:19 +00:00
|
|
|
)
|
2020-12-27 17:09:45 +00:00
|
|
|
|
|
|
|
// Provider returns a date instance.
|
|
|
|
type Provider interface {
|
|
|
|
Date() time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now is a date provider returning the current date.
|
|
|
|
type Now struct{}
|
|
|
|
|
|
|
|
func (n *Now) Date() time.Time {
|
|
|
|
return time.Now()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Frozen is a date provider returning always the same date.
|
|
|
|
type Frozen struct {
|
|
|
|
date time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewFrozenNow() Frozen {
|
|
|
|
return Frozen{time.Now()}
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewFrozen(date time.Time) Frozen {
|
|
|
|
return Frozen{date}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *Frozen) Date() time.Time {
|
|
|
|
return n.date
|
|
|
|
}
|
2021-05-11 19:53:19 +00:00
|
|
|
|
|
|
|
// TimeFromNatural parses a human date into a time.Time.
|
|
|
|
func TimeFromNatural(date string) (time.Time, error) {
|
|
|
|
if date == "" {
|
|
|
|
return time.Now(), nil
|
|
|
|
}
|
2021-12-17 17:57:03 +00:00
|
|
|
if t, err := time.Parse(time.RFC3339, date); err == nil {
|
|
|
|
return t, nil
|
|
|
|
}
|
2022-01-23 13:46:02 +00:00
|
|
|
if t, err := time.ParseInLocation("2006-01-02T15:04:05", date, time.Local); err == nil {
|
|
|
|
return t, nil
|
|
|
|
}
|
|
|
|
if t, err := time.ParseInLocation("2006-01-02T15:04", date, time.Local); err == nil {
|
|
|
|
return t, nil
|
|
|
|
}
|
|
|
|
if t, err := time.ParseInLocation("2006-01-02", date, time.Local); err == nil {
|
|
|
|
return t, nil
|
|
|
|
}
|
|
|
|
if t, err := time.ParseInLocation("2006-01", date, time.Local); err == nil {
|
|
|
|
return t, nil
|
|
|
|
}
|
|
|
|
if t, err := time.ParseInLocation("2006", date, time.Local); err == nil {
|
|
|
|
return t, nil
|
|
|
|
}
|
|
|
|
if t, err := time.ParseInLocation("15:04", date, time.Local); err == nil {
|
|
|
|
return t, nil
|
|
|
|
}
|
|
|
|
return naturaldate.Parse(date, time.Now(), naturaldate.WithDirection(naturaldate.Past))
|
2021-05-11 19:53:19 +00:00
|
|
|
}
|