K
K
kolyafat2020-04-14 21:49:37
go
kolyafat, 2020-04-14 21:49:37

Parse time golang, strange behaviour, but why?

Good time dear community. Maybe someone faced a similar problem, more like a bug. I tried to unmarshal the date string and it didn't work, this is what I came up with:

func (c *CustomDate) UnmarshalJSON(b []byte) (err error) {
  s := strings.Trim(string(b), `"`) 
  if s == "null" {
    return
  }
  t, err := time.Parse(time.RFC3339, time.RFC3339)
  if err != nil {
    return err
  }
  c.Time = t
  return
}

Why does this construct return a parse error? If it's really the point:
func main() {
  _, err := time.Parse(time.RFC3339, time.RFC3339)
  if err != nil {
    panic(err)
  }
}

How??? go 1.9
Thanks in advance to all who are interested.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2020-04-14
@kolyafat

Indeed, a strange design. And it looks like a bug. The time.Parse function accepts a time format and value. There are two identical arguments here.
Actually, in the example at the very bottom there is such a line where this error is described

U
uvelichitel, 2020-04-14
@uvelichitel

Because the constant const time.RFC3339 = "2006-01-02T15:04:05Z07:00", is not a valid time. Z in RFC3339 is the letter index for the time zone (Zulu in this case). The zone can also be denoted by the offset +07:00 Or this or that:
"2006-01-02T15:04:05Z"
or
"2006-01-02T15:04:05+07:00"
And the constant from the package is a valid template for parsing, but not valid time

K
kolyafat, 2020-04-15
@kolyafat

Thanks to the sympathetic people, I remove the question, I figured it out, the usual DAMN. I didn’t understand why it didn’t work, but not direct hands definitely helped. This is how it works:

const layout = "2006-01-02T15:04:05.99"

func (c *CustomDate) UnmarshalJSON(b []byte) (err error) {
  s := strings.Trim(string(b), `"`)
  if s == "null" {
    return
  }
  t, err := time.Parse(layout, s)
  if err != nil {
    return err
  }
  c.Time = t
  return
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question