Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String date to date [duplicate]

Tags:

date

go

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.

like image 832
Pankaj Khairnar Avatar asked Jun 21 '16 07:06

Pankaj Khairnar


People also ask

How to format a string date java?

Java SimpleDateFormat Example String pattern = "MM-dd-yyyy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String date = simpleDateFormat. format(new Date()); System. out. println(date);


2 Answers

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")
like image 50
ain Avatar answered Oct 10 '22 23:10

ain


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"
)
like image 29
Grokify Avatar answered Oct 11 '22 00:10

Grokify