2

How do I parse the date "3 Mar -1500" to represent 1500 BC?

https://play.golang.org/p/akqQPj4mLeo

1

1 Answer 1

3

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.