Natural date time parsing for Go. This project is a fork of tj/go-naturaldate. This package was designed for parsing human-friendly relative date/time ranges (e.g., "today", "5 minutes ago", "next month") in Apex Logs' command-line log search, but is flexible enough to be used in any Go project that requires natural language date parsing.
go get github.com/anatol/naturaldate.goUse naturaldate.Parse to parse a natural language date string into a time.Time. It requires a reference time (base or now) to resolve relative expressions.
package main
import (
"fmt"
"log"
"time"
"github.com/anatol/naturaldate.go"
)
func main() {
// Parse a basic relative time
t, err := naturaldate.Parse("5 minutes ago", time.Now())
if err != nil {
log.Fatal(err)
}
fmt.Println(t)
// You can also parse specific dates or times
t, err = naturaldate.Parse("December 25th at 7:30am", time.Now())
if err != nil {
log.Fatal(err)
}
fmt.Println(t)
}You can also parse a relative duration using naturaldate.ParseDuration.
d, err := naturaldate.ParseDuration("1 year and 2 months", time.Now())
if err == nil {
fmt.Println(d) // e.g., 10248h0m0s
}
p, err := naturaldate.ParseDuration("1 year and 2 months", time.Now(), naturaldate.WithDirection(naturaldate.Past))
if err == nil {
fmt.Println(p) // e.g., -10224h0m0s
}Here are some examples of the types of expressions currently supported. Arbitrary text is generally ignored (e.g., "Remind me in...").
nowtodayyesterday5 minutes agothree days agolast monthnext monthone year from nowyesterday at 10amlast sunday at 5:30pmsunday at 22:45next Januarylast FebruaryDecember 25th at 7:30am10am10:05pm10:05:22pmRestart the server in 5 days from nowRemind me on the 25th of December at 7:30amMessage me in two weeks
See the tests for more examples.
A default direction can be applied using naturaldate.WithDirection() for ambiguous expressions such as sunday, or september. By default, naturaldate.Past is used, so they will be equivalent to last sunday and last september.
// Treat "sunday" as "next sunday"
t, err := naturaldate.Parse("sunday", time.Now(), naturaldate.WithDirection(naturaldate.Future))To build the parser first install pointlander/peg, then run go generate:
go get github.com/pointlander/peg
go generate ./...