go - 时间包中的 "Handy time stamps"是做什么用的?

标签 go

引用:

我想弄清楚“Handy Time Stamp”在时间包中的用途。

我可以使用其他常量(例如 RFC)很好地解析日期

t, _ := time.Parse(time.RFC822, "02 Jan 06 15:04 MST")
fmt.Println(t.Unix())
Output 1136214240

对比

t, _ := time.Parse(time.Stamp, "Jan _2 15:04:05")
fmt.Println(t.Unix())
Output: -62135596800

最后的输出是错误的。我在这里错过了什么?这些时间戳有什么用?

下面是时间常数的 Godoc:

const (
        ANSIC       = "Mon Jan _2 15:04:05 2006"
        UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
        RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
        RFC822      = "02 Jan 06 15:04 MST"
        RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
        RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
        RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
        RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
        RFC3339     = "2006-01-02T15:04:05Z07:00"
        RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
        Kitchen     = "3:04PM"
        // Handy time stamps.
        Stamp      = "Jan _2 15:04:05"
        StampMilli = "Jan _2 15:04:05.000"
        StampMicro = "Jan _2 15:04:05.000000"
        StampNano  = "Jan _2 15:04:05.000000000"
)

最佳答案

The last output is wrong. What am I missing here? How are these timestamps useful?

你肯定漏掉了这里的错误检查,让我们添加它

t, err := time.Parse(time.Stamp, "Jan _2 15:04:05")
fmt.Println(err)
fmt.Println(t.Unix())

输出:

parsing time "Jan _2 15:04:05" as "Jan _2 15:04:05": cannot parse "_2 15:04:05" as "_2" -62135596800

正确的字符串应该是“Jan 2 15:04:05”(注意 Jan 和 2 之间的双空格)。关于文档中的下划线:

Within the format string, an underscore _ represents a space that may be replaced by a digit if the following number (a day) has two digits; for compatibility with fixed-width Unix time formats.

那么,为什么它表示为 UNIX 时间是负数,让我们检查一下:

t, err := time.Parse(time.Stamp, "Jan  2 15:04:05")
fmt.Println(err)
fmt.Println(t)

输出:

<nil>
0000-01-02 15:04:05 +0000 UTC

所以它是负数,因为年份是 0000。

最后,它可以用在什么地方?例如,测量耗时操作的持续时间。您可以以一种 Stamp 格式输出日志当前时间以及一些消息,如“开始做这个”、“完成做那个”。然后,因为它是固定宽度格式并且没有不必要的年份信息 - 很容易阅读日志,也很容易解析此类日志。

*nix 中的“syslog”实际上使用了这种格式。

关于go - 时间包中的 "Handy time stamps"是做什么用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21465082/

相关文章:

go - 单值上下文中的多个值

go - goroutine不会将内存返回操作系统

如果不匹配,Golang 模板将忽略

testing - 当一个具体方法的签名引用另一个具体类型而不是它的接口(interface)时,我如何模拟多个类型?

go - 如何在 Golang 中并行生成组合

image - 为什么来自 Bild 的 jpeg.Decode(bytes.NewReader(imageBytes)) 和 jpeg.Encode(buf, img, nil) 占用大量 CPU?

go - 如何提取嵌套的 JSON 数据?

go - 如何理解core/types/block.go中的 'rlpHash'方法

postgresql - 戈朗 : gorm use Find(&model) for non gorm migrate table

if-statement - "if"具有多个返回值的方法的初始化语句