Home > OS >  In Parse() function, why the time.ANSIC layout didn't work in Go?
In Parse() function, why the time.ANSIC layout didn't work in Go?

Time:02-12

I am currently studying time library and I am not sure why the time.ANSIC at layout part didn't work what I expected. In Parse() function there is a syntax func Parse (layout, value string) and based on my understanding I can use in layout part like time.UnixDate, ANSIC, RFC3339 etc.

When I code like below

const layout = "Jan 2, 2006 at 3:04pm (MST)"
    sm, _ := time.Parse(layout, "Feb 4, 2014 at 6:05pm (PST)")
    fmt.Println(sm)

It works as well and I got 2014-02-04 18:05:00 0000 PST.

However, when I add time.ANSIC at layout part

tm, _ := time.Parse(time.ANSIC, "Feb 4, 2014 at 6:05pm (PST)")
    fmt.Println(tm)

I got 0001-01-01 00:00:00 0000 UTC.

I am not sure why do I get any time. I really appreciate your help!

CodePudding user response:

It is not idiomatic Go to discard errors returned from any of the methods in standard library. Always check them before processing your returned value.

If you had noticed the error from your parse function, you would see that the layout for time.ANSIC is not compatible with the date string that you are trying to parse

parsing time "Feb 4, 2014 at 6:05pm (PST)" as "Mon Jan _2 15:04:05 2006": cannot parse "Feb 4, 2014 at 6:05pm (PST)" as "Mon"

From https://pkg.go.dev/time#Parse

The second argument must be parseable using the format string (layout) provided as the first argument.

https://go.dev/play/p/jU-EvL5W3Hp

  •  Tags:  
  • go
  • Related