This simple library uses a custom PEG grammar to parse and evaluate time expressions.
It allows you to write time expressions in a natural language and evaluate them
to a time.Time object.
package main
import (
"fmt"
"time"
"github.com/Zenithar/timexpr"
)
func main() {
// Parse the expression
ts, err := timexpr.Parse("tomorrow")
if err != nil {
panic(err)
}
fmt.Println(ts.Format(time.RFC3339))
}The following expressions are supported:
now: returns the current timetoday: returns the current date at midnighttomorrow: returns the current time + 1 dayyesterday: returns the current time - 1 daynext (NUMBER)? UNIT: returns the current time + NUMBER UNITlast (NUMBER)? UNIT: returns the crrent time - NUMBER UNITNUMBER UNIT (ago|later|sooner): returns the reference time - NUMBER UNIT
Where UNIT can be one of the following:
s/sec/second/secondsfor secondsm/min/minute/minutesfor minutesh/hour/hoursfor hoursd/day/daysfor daysw/week/weeksfor weeksM/month/monthsfor monthsy/year/yearsfor years
To generate the parser, you need to install the pigeon tool:
go install github.com/mna/pigeon@latestThen you can generate the parser:
cd internal/parser
pigeon -optimize-parser -optimize-basic-latin -o grammar.go grammar.pegThis project is licensed under the MIT License - see the LICENSE file for details.