Why my code not parsing string correctly into date?

I’ve the this code:

package main

import (
	"fmt"
	"time"
)

const (
	layoutISO = "2006-01-02"
	layoutUS  = "January 2, 2006"
	custom    = "%mm/%dd%yy"
)

func main() {
	date := "12/31/19" // "1999-12-31"
	t, _ := time.Parse(custom, date)
	fmt.Println(t)                  // 1999-12-31 00:00:00 +0000 UTC
	fmt.Println(t.Format(layoutUS)) // December 31, 1999
}

But it is returning wrong result, it return:

0001-01-01 00:00:00 +0000 UTC
January 1, 0001

Where is my mistake?

Go doesn’t use formatting parameters like %Y, %d, etc. It uses a “magic” date: 2006-01-02 15:04:05-0700.

To parse 12/31/19 (did you mean 12/31/99?), use time.Parse("01/02/06", "12/31/19").

Great, thanks a lot.

I understand my error was, I was thinking the format to be used is the format required to re-write the date in, while it should be the format the given date/string is in.
in my case, the input date format is 12/31/19, which is m/d/y so using 1 for month, 2 for day, and 2006 or 1061 for year, then it should be written as 1/2/06, if my date is 12/31/2019 then it should be written as 1/2/2006, below code is the one worked:

package main

import (
	"fmt"
	"time"
)

const (
	layoutISO = "2006-01-02"
	layoutUS  = "January 2, 2006"
	custom    = "1/2/06"
)

func main() {
	date := "12/31/19" 
	t, err := time.Parse(custom, date)   // format of input string is: custom, NO other format can be used.
	fmt.Println(t, err)            
	fmt.Println(t.Format(layoutUS)) // format of printing the date is: layoutUS, ALL other formats can be used.
}

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