Parsing dates in Go

Ensure the reference time ("Mon Jan 2 15:04:05 -0700 MST 2006") is used in layout string.

For example:

package main

import (
        "fmt"
        "time"
)

func main() {
        goodLayout := "January 2 2006"
        if t, err := time.Parse(goodLayout, "March 10 2019"); err != nil {
                    fmt.Printf("%s\n", err)
        } else {
                    fmt.Printf("%v\n", t)
        }

        badLayout := "January 2 2009"
        if t, err := time.Parse(badLayout, "March 10 2019"); err != nil {
                    fmt.Printf("%s\n", err)
        } else {
                    fmt.Printf("%v\n", t)
        }
}
2019-03-10 00:00:00 +0000 UTC
parsing time "March 10 2019" as "January 2 2009": cannot parse "19" as "009"

Comments

Popular posts from this blog

Back to 2019

Easy Ways to Save Money

Although often overshadowed by the Ancient Greeks, the Ancient Romans also had a rich culture and produced many must-read books