time.Parse with custom layout

2019-08-04 09:02发布

I'm trying to parse this string pattern "4-JAN-12 9:30:14" into a time.Time.

Tried time.Parse("2-JAN-06 15:04:05", inputString) and many others but cannot get it working.

I've read http://golang.org/pkg/time/#Parse and https://gobyexample.com/time-formatting-parsing but it seems there aren't any examples like this.

Thanks!

Edit: full code:

type CustomTime time.Time

func (t *CustomTime) UnmarshalJSON(b []byte) error {
    auxTime, err := time.Parse("2-JAN-06 15:04:05", string(b))
    *t = CustomTime(auxTime)
    return err
}

parsing time ""10-JAN-12 11:20:41"" as "2-JAN-06 15:04:05": cannot parse ""24-JAN-15 10:27:44"" as "2"

标签: parsing time go
1条回答
啃猪蹄的小仙女
2楼-- · 2019-08-04 09:40

Don't know what you did wrong (should post your code), but it is really just a simple function call:

s := "4-JAN-12 9:30:14"
t, err := time.Parse("2-JAN-06 15:04:05", s)
fmt.Println(t, err)

Outputs:

2012-01-04 09:30:14 +0000 UTC <nil>

Try it on the Go Playground.

Note that time.Parse() returns 2 values: the parsed time.Time value (if parsing succeeds) and an optional error value (if parsing fails).

See the following example where I intentionally specify a wrong input string:

s := "34-JAN-12 9:30:14"

if t, err := time.Parse("2-JAN-06 15:04:05", s); err == nil {
    fmt.Println("Success:", t)
} else {
    fmt.Println("Failure:", err)
}

Output:

Failure: parsing time "34-JAN-12 9:30:14": day out of range

Try it on the Go Playground.

EDIT:

Now that you posted code and error message, your problem is that your input string contains a leading and trailing quotation mark!

Remove the leading and trailing quotation mark and it will work. This is your case:

s := `"4-JAN-12 9:30:14"`

s = s[1 : len(s)-1]
if t, err := time.Parse("2-JAN-06 15:04:05", s); err == nil {
    fmt.Println("Success:", t)
} else {
    fmt.Println("Failure:", err)
}

Output (try it on the Go Playground):

Success: 2012-01-04 09:30:14 +0000 UTC
查看更多
登录 后发表回答