Convert String to time.Time (timestamp)

Hi,

I want to convert any entered string to time.Time format like:-

Given String can be “27/12/2021 18:19” or “27/12/2021 18:19:02”
to “27/12/2021 18:19:00” or “27/12/2021 18:19:02”.

I have used time.Parse(layout, given_string) where layout = “02/01/2006 15:04:05”

But it was working fine for 2nd case and for 1st case it returns parse error.

In Go can convert any string to given layout by add 0’s to the missed part?

Thanks in Advance

Parse with one format, and it it fails, try the other.

Can we do this in single case?

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

No mention of optional parts of the format other than fractional seconds.

I don’t see what is so onerous in exchange for a surprise-free API.

func ParseTimeWithFallback(layout, fallbackLayout, value string) (Time,error) {
  t, e := time.Parse(layout, value)
  if e!=nil {
    t, e = time.Parse(fallbackLayout, value)
  }
  return t,e
}

when I have to deal with date parser in string format I use the dateparse library, so I don’t have to deal with all cases.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.