在Golang中显示当前日期和时间

Go当前时间教程展示了如何在Golang中显示当前日期和时间。time包提供了测量和显示时间的功能。

Now函数返回当前本地时间。

Format函数返回根据布局格式化的时间值的文本表示。布局是预定义的常量值或参考日期时间的特定格式:MonJan215:04:05-0700MST2006

$ go version
go version go1.18.1 linux/amd64

我们使用Go版本1.18。

转到当前时间示例

以下示例打印当前日期和时间。

package main

import (
    "fmt"
    "time"
)

func main() {

    now := time.Now()

    fmt.Println("The current datetime is:", now)
}

该示例使用Now打印当前时间。

$ go run current_time.go 
The current datetime is: 2020-05-26 18:56:03.268250331 +0200 CEST m=+0.000060798

转到当前时间部分

在下面的例子中,我们打印了当前时间的各个部分。

package main

import (
    "fmt"
    "time"
)

func main() {

    now := time.Now()

    fmt.Println("Year:", now.Year())
    fmt.Println("Month:", now.Month())
    fmt.Println("Day:", now.Day())
    fmt.Println("Hour:", now.Hour())
    fmt.Println("Minute:", now.Minute())
    fmt.Println("Second:", now.Second())
    fmt.Println("Nanosecond:", now.Nanosecond())
}

在代码示例中,我们分别使用相应的函数打印年、月、日、时、分、秒和纳秒。

$ go run current_time_parts.go 
Year: 2020
Month: May
Day: 26
Hour: 19
Minute: 1
Second: 12
Nanosecond: 985372280

格式化当前时间

Go不使用典型的yyyy-mm-dd格式说明符;它使用以下参考日期时间格式:

Mon Jan 2 15:04:05 -0700 MST 2006

我们格式化时间如何构造这个特定的参考日期时间。

package main

import (
    "fmt"
    "time"
)

func main() {

    now := time.Now()

    fmt.Println("Time: ", now.Format("15:04:05"))
    fmt.Println("Date:", now.Format("Jan 2, 2006"))
    fmt.Println("Timestamp:", now.Format(time.Stamp))
    fmt.Println("ANSIC:", now.Format(time.ANSIC))
    fmt.Println("UnixDate:", now.Format(time.UnixDate))
    fmt.Println("Kitchen:", now.Format(time.Kitchen))
}

该示例以自定义和预定义格式显示当前时间。

fmt.Println("Date:", now.Format("Jan 2, 2006"))

这是自定义日期时间格式的示例。

fmt.Println("ANSIC:", now.Format(time.ANSIC))

这是预定义格式的示例。

$ go run current_time_format.go 
Time:  19:07:53
Date: May 26, 2020
Timestamp: May 26 19:07:53
ANSIC: Tue May 26 19:07:53 2020
UnixDate: Tue May 26 19:07:53 CEST 2020
Kitchen: 7:07PM

在本教程中,我们展示了如何在Golang中显示当前日期时间。

列出所有Go教程。

赞(0) 打赏

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏