Parsing dates with negative year in Go?
Parsing dates with negative year in Go?
How do I parse the date "3 Mar -1500" to represent 1500 BC?
https://play.golang.org/p/akqQPj4mLeo
1 Answer
1
Here is a first draft that illustrates the concept:
package main
import (
"fmt"
"strings"
"time"
)
func parseCEDate(value string) (time.Time, error) {
const layout = "_2 Jan 2006"
date, err := time.Parse(layout, value)
if err == nil {
return date, err
}
perr, ok := err.(*time.ParseError)
if !ok {
return time.Time{}, err
}
if perr.LayoutElem != "2006" {
return time.Time{}, err
}
if !strings.HasPrefix(perr.ValueElem, "-") {
return time.Time{}, err
}
value = strings.Replace(value, perr.ValueElem, perr.ValueElem[1:], 1)
date, derr := time.Parse(layout, value)
if derr != nil {
return time.Time{}, err
}
return date.AddDate(-2*date.Year(), 0, 0), derr
}
func main() {
fmt.Println(parseCEDate("3 Mar -1500"))
fmt.Println(parseCEDate("3 Mar 1500"))
}
Playground: https://play.golang.org/p/QtZ5BBSJmHJ
Output:
-1500-03-03 00:00:00 +0000 UTC <nil>
1500-03-03 00:00:00 +0000 UTC <nil>
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
According to the time.Parse function documentation: Years must be in the range 0000..9999.
– Ortomala Lokni
13 hours ago