定义自定义时间格式

Define custom time format

我正在尝试根据我的应用程序的要求编写自定义日期格式字符串。 使用 Go 时间包,我使用笨拙的函数获取格式(见下文)。

此外,由于这个函数每天都会被调用数百万次,所以我希望它也能非常高效。 Go 中是否有可用的 POSIX 样式格式?

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    fmt.Printf("Time now is %d%02d%02d%02d%02d%02d",
        t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
}

在 Go 中有内置布局传递给 Time (see func (Time) Format) 的 .Format() 方法,其中之一可能是您正在寻找的:

func main() {
    fmt.Println(time.Now().Format(time.ANSIC))
    fmt.Println(time.Now().Format(time.UnixDate))
    fmt.Println(time.Now().Format(time.RFC3339))
}

这将比 fmt.Printf("...", t.Year(), t.Month(), ...) 快,但我们在这里讨论的是微秒 "faster",因此实际上没有太大区别。

输出:

Sun Jun 10 13:18:09 2018
Sun Jun 10 13:18:09 UTC 2018
2018-06-10T13:18:09Z

还有更多预定义布局,因此您可以检查所有布局,看看其中是否符合您的需要。这里他们直接来自源代码:

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 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.

因此,例如:

fmt.Println(time.Now().Format("Mon January 2, 2006 - 15:04:05.000"))

给出:

Sun June 10, 2018 - 17:49:32.557

如果你想要一些不同的东西,你只需要格式化日期Jan 2 15:04:05 2006 MST你希望它如何显示。你也可以看看the relative page 在 Go by Example 上。