Convert String to Date in yyyy-mm-dd format

Hi,

I am parsing one csv file, file has Date data, and I want to compare this string Date with other Date,

So someone can help to convert String to Date,

Is it possible to convert string date to YYYY-MM-DD format ?

Thanks
Alpesh

Yes.

yourDate, err := time.Parse("2006-01-02", yourString)

See time.Parse and the package constants for layout examples.

Or, if you are accustomed to strftime, see http://fuckinggodateformat.com for conversion help.

5 Likes

:D :D :D 

(Although I confess the only parts of it I have difficulty with these days are the time zone things. It’s more the concept of it that’s annoying than the day to day usage.)

1 Like

If you’re new to Go, the time constants might seem weird (the 2006-01-02 written by @nathankerr), but they actually have a reason. Instead of having a conventional format to print the date, Go uses a reference date which seems meaningless but if you see it this way it makes sense: it’s 1 2 3 4 5 6 in the Posix date format:

Mon Jan 2 15:04:05 -0700 MST 2006
0   1   2  3  4  5              6

The timezone in the middle would have been the 7 piece (someone has an insight on why -0600 MST 2007 wasn’t chosen instead?)

1 Like

IIRC, it’s based on the order of what date printed once when Rob ran it on some random box with some random, probably North American, locale. I guess it had the time zone after the year.

And it’s this gratuitous arbitrariness that grates on me in an otherwise well thought out language / standard library, not so much how hard it is to learn to use in the end.

3 Likes

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