'Parsing RFC-3339 date string to time.Time [duplicate]
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 1:[1]
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 mogo/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"
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
