Reputation: 1256
Given a time variable, I want to print year, month, and day. From the documentation, it seems that any layout can be used. For example, I don't see difference between layouts 2006-01-02, 2006-10-10, 1999-02-02.
However, only layout 2006-01-02 returns what I expect. Where can I find documentation on the meanings of '2006', '01', '02' in the layout?
I played here with different layouts: go playground: testing layouts
Upvotes: 24
Views: 27947
Reputation: 11052
to follow up on Jack's info, see the detailed examples:
// 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
this reference time allows us to clarify whether go should parse 01-02-17 as jan 2 2017 or feb 1
Upvotes: 29
Reputation: 2277
Go’s time formatting unique and different than what you would do in other languages. Instead of having a conventional format to print the date, Go uses the reference date 20060102150405
which seems meaningless but actually has a reason, as it’s 1 2 3 4 5 6
in the Posix date command:
Mon Jan 2 15:04:05 -0700 MST 2006
0 1 2 3 4 5 6
In Go layout string is:
Jan 2 15:04:05 2006 MST
1 2 3 4 5 6 -7
Upvotes: 31
Reputation: 21163
Mon Jan 2 15:04:05 -0700 MST 2006
is the reference time, which means the layout needs to use that exact date. There's more information here, but basically by using unique values for each part of a datetime it's able to tell where each part (year, month, etc) actually is automatically.
Upvotes: 17