index rss mastodon twitter github linkedin email
Álvaro Ramírez
sponsor

Álvaro Ramírez

19 February 2019 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"