Home > Software design >  Golang parsing date in RFC822Z format without leading zero
Golang parsing date in RFC822Z format without leading zero

Time:12-06

I have a date string I can't control that I'm trying to parse into a Date.

The format most closely resembles RFC822Z.

RFC822Z = "02 Jan 06 15:04 -0700"

Reference: https://yourbasic.org/golang/format-parse-string-time-date-example/

However, it does not have the leading zero.

Example: "5 Dec 2022 20:15:21 0000"

The way I saw in other posts, is to write a manual format.

parseTime, timeParseError = time.Parse("2 Jan 2006 15:04:21 -0700", stringDate)

However, when I try that, I get a warning:

parsing time "2 Jan 2006 15:04:21 -0700" as "2 Jan 2006 15:04:21 -0700": cannot parse " -0700" as "1" (SA1002)

Running it despite the warning fails to part, unsurprisingly.

CodePudding user response:

Your time format doesn't match - in your example you have "5 Dec 2022", but you are using "2 Jan 06", and in your reference format you hvae "15:04:21" but it should be "15:04:05".

Your reference format should be 2 Jan 2006 15:04:05 -0700 not 2 Jan 06 15:04:21 -0700

https://go.dev/play/p/Shc381WgB6_7

CodePudding user response:

this seems to do it:

package time

import "time"

func parse(value string) (time.Time, error) {
   return time.Parse("2 Jan 2006 15:04:05 -0700", value)
}

https://godocs.io/time#pkg-constants

  • Related