Assume we have the following code:
t := time.Now()
fmt.Println(t.Format("yyyyMMddHHmmss"))
How can we format the date in the format: yyyyMMddHHmmss
? The question is very simple and the answer is almost trivial. However, the reason for this answer conceals one of the great nightmares of programmers writing with GoLang.
To format the date simply enter fmt.Println(t.Format("20060102150405"))
. Hmm, it looks very strange at first glance. Why do we include a date? And why 2 January 2006?
It actually turns out that behind this absurd, hand-picked date, there is a very clever engineering choice. The ‘Parse’ function that is used to parse a string does not use any parsing rules, but relies on the ‘query-by-example’. The query-by-example is a technique for parsing a string based on an example query that is compared with the parsed string.
This date was chosen for the timestamp representation of the date; in fact if we took the date (Mon Jan 2 15:04:05 -0700 MST 2006 ), we would find that:
Go’s code does indeed mention the query-by-example:
// The layout string used by the Parse function and Format method
// shows by example how the reference time should be represented.
// We stress that one must show how the reference time is formatted,
// not a time of the user's choosing. Thus each layout string is a
// representation of the time stamp,
// Jan 2 15:04:05 2006 MST
// An easy way to remember this value is that it holds, when presented
// in this order, the values (lined up with the elements above):
// 1 2 3 4 5 6 -7
Some details and a historical discussion can be found on Github.