ijt / go-anytime

Parse natural and standardized dates/times and ranges in Go without knowing the format in advance
MIT License
23 stars 2 forks source link

Handle tricky implicit ranges #1

Closed ijt closed 2 years ago

ijt commented 2 years ago

Description

I'm currently working on implicit date ranges like "today", "last week", and the like. For example, "today" begins at 0:0:0 today and ends at 0:0:0 tomorrow, exclusive, so that defines a range.

One way to detect those ranges in many cases is to find the first time field that is a default (1 for date fields, 0 for time fields) and then go up a level and add one unit of that. So for example with "today" you typically find that the first defaulted field is the hours (truncated to 0) and so you add a day (24h) to today and get tomorrow at 0:0:0. However, that fails in cases like when the user specifies Jan 2022 since Jan is month 1. They don't mean all of the year 2022. They mean the month of January in 2022.

So the resolution info has to come through somehow, though it's not currently available in the parser generated by RangeParser(). One way to solve the problem would be to have the datetime Parser() func make a parser returning a Range. Probably to make it more explicit, the Range would be changed to have a start time and a duration. The duration would only be used when the datetime is used as an implicit range.

That affects the API, though the change can be kept to a minimum. The result of Parser() can return a Range, so that is different. However, Parse() can still extract the time.Time and return that as before.

How do we do this in a way that keeps code changes and risk to a minimum? One way would be to embed the start time in the range so you can use it as a time, keeping a lot of code unchanged:

type Range struct {
    time.Time
    Duration time.Duration
}

func (r Range) Start() time.Time {
    return r.time.Time  // not sure about the exact syntax here
}

func (r Range) End() time.Time {
    return r.Start().Add(r.Duration)
}
ijt commented 2 years ago

Closed as of bbd41cc8c26fd2de660be64c2a710675e9fd5cb7.