Go:time.Format:如何理解'2006-01-02'布局的含义?

mko*_*kho 2 time go

鉴于时间变量,我想打印年,月和日.从文档中,似乎可以使用任何布局.例如,我看不到布局2006-01-02,2006-10-10,1999-02-02之间的区别.

但是,只有布局2006-01-02会返回我期望的内容.我在哪里可以找到有关'2006','01','02'在布局中的含义的文档?

我在这里玩不同的布局:去游乐场:测试布局

Jac*_*ack 7

Mon Jan 2 15:04:05 -0700 MST 2006是参考时间,这意味着布局需要使用该确切日期.这里有更多的信息,但基本上通过对日期时间的每个部分使用唯一值,它能够告诉每个部分(年,月等)实际上是自动的.

纠正去游乐场


Pla*_*ato 5

要跟踪Jack的信息,请参见详细示例

// 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
Run Code Online (Sandbox Code Playgroud)

此参考时间使我们可以确定go应该将01-02-17解析为2017年1月2日还是2月1日。

  • 谢谢,这说明了一切:“我们强调必须显示参考时间的格式,而不是用户选择的时间”。遗憾的是,示例中隐藏了如此重要的信息。 (2认同)
  • 唉,所以 Go 作者为他们的参考日期选择了一个助记符,但随后他们使该助记符对应于一些无意义的月-日-时-分-秒-年偏移顺序,并选择了 UTC-7 而不是 UTC+7。啊? (2认同)

Ash*_*ari 5

Go 的时间格式与您在其他语言中所做的不同。Go 没有使用传统格式来打印日期,20060102150405而是使用参考日期,这看起来毫无意义但实际上是有原因的,因为它1 2 3 4 5 6在 Posix date 命令中:

Mon Jan 2 15:04:05 -0700 MST 2006
0   1   2  3  4  5              6
Run Code Online (Sandbox Code Playgroud)

在 Go 布局字符串是:

Jan 2 15:04:05 2006 MST
1   2  3  4  5    6  -7
Run Code Online (Sandbox Code Playgroud)

检查这个