Isaac Melton
Isaac Melton

Reputation: 31

Parsing a golang time object from an incomplete string

I have the following date string: 2017-09-04T04:00:00Z

I need to parse this string into a golang time in order to have uniform data across my application. Here is the code so far:

parsedTime := "2017-09-04T04:00:00Z"
test, err := time.Parse(time.RFC3339, parsedTime)
check(err)
fmt.Println(test)

I get the following error when I try to run the program:

": extra text: 0:00 +0000 UTC parsing time "2017-09-04T04:00:00Z

How can I either add the extra text that it is looking for or get the parser to stop looking after the Z?

I have also tried the following:

parsedTime := "2017-09-04T04:00:00Z"
test, err := time.Parse("2006-01-02T03:04:05Z", parsedTime)
check(err)
fmt.Println(test)

Which returns the following error:

": extra text: 017-09-04T04:00:00Z

Upvotes: 2

Views: 2558

Answers (1)

John Weldon
John Weldon

Reputation: 40739

Both formats you used work with the current version of go: https://play.golang.org/p/Typyq3Okrd

var formats = []string{
    time.RFC3339,
    "2006-01-02T03:04:05Z",
}

func main() {
    parsedTime := "2017-09-04T04:00:00Z"

    for _, format := range formats {
        if test, err := time.Parse(format, parsedTime); err != nil {
            fmt.Printf("ERROR: format %q resulted in error: %v\n", format, err)
        } else {
            fmt.Printf("format %q yielded %s\n", format, test)
        }
    }
}

Can you provide a working example that demonstrates your problem? You can use the go playground for shareable snippets.

Upvotes: 1

Related Questions