【问题标题】:Go: time.Format: how to understand meaning of '2006-01-02' layout?去:time.Format:如何理解'2006-01-02'布局的含义?
【发布时间】:2017-02-14 03:21:08
【问题描述】:

给定一个时间变量,我想打印年、月和日。 从文档来看,似乎可以使用任何布局。例如,我看不出布局 2006-01-02、2006-10-10、1999-02-02 之间的区别。

但是,只有布局 2006-01-02 会返回我所期望的。 我在哪里可以找到有关布局中“2006”、“01”、“02”含义的文档?

我在这里玩过不同的布局:go playground: testing layouts

【问题讨论】:

  • 您问“我在哪里可以找到关于布局 [包 p 的函数 f] 中 [... some detail] 含义的文档?”答案总是一样的:在包 p 的文档中(始终阅读完整的包文档!)和函数 f 的文档(也阅读它;两次)。 doc 没有短路:不要猜测,不要基于签名假设,不要仅在函数 doc 上进行实验:先阅读包 doc,然后是函数 doc。必要时重复。运行示例。

标签: go time


【解决方案1】:

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

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

在 Go 中的布局字符串是:

Jan 2 15:04:05 2006 MST
1   2  3  4  5    6  -7

查看this

【讨论】:

    【解决方案2】:

    要跟进杰克的信息,请查看详细信息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
    

    这个参考时间让我们能够澄清 go 是否应该将 01-02-17 解析为 2017 年 1 月 2 日或 2 月 1 日

    【讨论】:

    • 谢谢,这说明了一切:“我们强调必须显示参考时间的格式,而不是用户选择的时间”。遗憾的是,示例中隐藏了如此重要的信息。
    【解决方案3】:

    Mon Jan 2 15:04:05 -0700 MST 2006 是参考时间,这意味着布局需要使用该确切日期。有more information here,但基本上通过对日期时间的每个部分使用唯一值,它能够自动判断每个部分(年、月等)的实际位置。

    Corrected go playground

    【讨论】:

      猜你喜欢
      • 2011-05-07
      • 2015-08-31
      • 1970-01-01
      • 2014-12-28
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 2011-08-03
      相关资源
      最近更新 更多