String date to date

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")

In addition to using a literal 2006-01-02 time format, you reduce errors by creating a constant similar to how Go does it in the time package.

The YYYY-MM-DD format is defined as full-date in RFC-3339 as follows (order adjusted):

full-date       = date-fullyear "-" date-month "-" date-mday
date-fullyear   = 4DIGIT
date-month      = 2DIGIT  ; 01-12
date-mday       = 2DIGIT  ; 01-28, 01-29, 01-30, 01-31 based on
                          ; month/year

So you can create a constant like the following to go along with the built-in time.RFC3339 and time.RFC3339Nano constants.

const RFC3339FullDate = "2006-01-02"

Then you can write the following:

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

This is in the gotilla/time/timeutil package, so you can write:

t, err := time.Parse(timeutil.RFC3339FullDate, "2011-01-19")

For reference, time/format.go contains the following constants:

const (
    ANSIC       = "Mon Jan _2 15:04:05 2006"
    UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
    RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
    RFC822      = "02 Jan 06 15:04 MST"
    RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
    RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
    RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
    RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
    RFC3339     = "2006-01-02T15:04:05Z07:00"
    RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
    Kitchen     = "3:04PM"
    // Handy time stamps.
    Stamp      = "Jan _2 15:04:05"
    StampMilli = "Jan _2 15:04:05.000"
    StampMicro = "Jan _2 15:04:05.000000"
    StampNano  = "Jan _2 15:04:05.000000000"
)

Tags:

Date

Go