Parsing RFC-3339 date string to time.Time

Issue

How to convert string date format to date, I have date string in format of:

YYYY-MM-DD 

Following I tried with no luck.

t, err := time.Parse("%Y-%m-%d", "2011-01-19")
t, err := time.Parse("YYYY-MM-DD", "2011-01-19")
t, err := time.Parse("2016-01-20", "2011-01-19")

all above statements are giving parse errors.

Solution

Please read the documentation of the time.Parse:

The layout defines the format by showing how the reference time, defined to be

Mon Jan 2 15:04:05 -0700 MST 2006

would be interpreted if it were the value; it serves as an example of the input format. The same interpretation will then be made to the input string.

So the correct format is

t, err := time.Parse("2006-01-02", "2011-01-19")

Answered By – ain

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.