Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: time.Format: how to understand meaning of '2006-01-02' layout?

Tags:

time

go

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

like image 895
mkokho Avatar asked Feb 14 '17 03:02

mkokho


People also ask

What is a valid GO time format literal?

Golang Time Format YYYY-MM-DD.

How do I change the format of time in Golang?

Golang supports time formatting and parsing via pattern-based layouts. To format time, we use the Format() method which formats a time. Time object. We can either provide custom format or predefined date and timestamp format constants are also available which are shown as follows.


2 Answers

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.

Corrected go playground

like image 146
Jack Avatar answered Sep 23 '22 14:09

Jack


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

like image 25
Plato Avatar answered Sep 22 '22 14:09

Plato