Context.Time applied the parsed month while the day was still the one of the reference date. When that day does not exist in the target month, time.Date normalizes it forward, so "september 5th" parsed on the 31st of October resolved to the 5th of October. The parsed day was only applied afterwards, to the already wrong month. Clamp the reference day to the last day of the target month before switching the month. The parsed day still overwrites it afterwards, so the ordering of the branches in Context.Time is unchanged. The existing fixtures pin the reference date to 2016-01-06 and the 6th exists in every month, so the overflow never triggered. Add a regression test that parses against 2016-10-31. Fixes #12
83 lines
1.9 KiB
Go
83 lines
1.9 KiB
Go
package rules
|
|
|
|
import "time"
|
|
|
|
type Context struct {
|
|
Text string
|
|
|
|
// accumulator of relative values
|
|
Duration time.Duration
|
|
|
|
// Aboslute values
|
|
Year, Month, Weekday, Day, Hour, Minute, Second *int
|
|
|
|
Location *time.Location
|
|
}
|
|
|
|
func (c *Context) Time(t time.Time) (time.Time, error) {
|
|
if t.IsZero() {
|
|
t = time.Now()
|
|
}
|
|
|
|
if c.Duration != 0 {
|
|
t = t.Add(c.Duration)
|
|
}
|
|
|
|
if c.Year != nil {
|
|
t = time.Date(*c.Year, t.Month(), t.Day(), t.Hour(),
|
|
t.Minute(), t.Second(), t.Nanosecond(), t.Location())
|
|
}
|
|
|
|
if c.Month != nil {
|
|
month := time.Month(*c.Month)
|
|
|
|
// time.Date would normalize a day the target month lacks into the next
|
|
// one; clamp instead.
|
|
day := t.Day()
|
|
if last := daysIn(month, t.Year()); day > last {
|
|
day = last
|
|
}
|
|
|
|
t = time.Date(t.Year(), month, day,
|
|
t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), t.Location())
|
|
}
|
|
|
|
if c.Weekday != nil {
|
|
diff := int(time.Weekday(*c.Weekday) - t.Weekday())
|
|
t = time.Date(t.Year(), t.Month(), t.Day()+diff, t.Hour(),
|
|
t.Minute(), t.Second(), t.Nanosecond(), t.Location())
|
|
}
|
|
|
|
if c.Day != nil {
|
|
t = time.Date(t.Year(), t.Month(), *c.Day, t.Hour(),
|
|
t.Minute(), t.Second(), t.Nanosecond(), t.Location())
|
|
}
|
|
|
|
if c.Hour != nil {
|
|
t = time.Date(t.Year(), t.Month(), t.Day(), *c.Hour,
|
|
t.Minute(), t.Second(), t.Nanosecond(), t.Location())
|
|
}
|
|
|
|
if c.Minute != nil {
|
|
t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(),
|
|
*c.Minute, t.Second(), t.Nanosecond(), t.Location())
|
|
}
|
|
|
|
if c.Second != nil {
|
|
t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(),
|
|
t.Minute(), *c.Second, t.Nanosecond(), t.Location())
|
|
}
|
|
|
|
if c.Location != nil {
|
|
t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(),
|
|
t.Minute(), t.Second(), t.Nanosecond(), c.Location)
|
|
}
|
|
|
|
return t, nil
|
|
}
|
|
|
|
// daysIn returns the number of days in the given month of the given year.
|
|
func daysIn(m time.Month, year int) int {
|
|
return time.Date(year, m+1, 0, 0, 0, 0, 0, time.UTC).Day()
|
|
}
|