ZetCode

Go 当前时间

最后修改时间 2024 年 4 月 11 日

在本文中,我们将展示如何在 Golang 中显示当前日期和时间。time 包提供了测量和显示时间的功能。

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

Format 函数根据布局返回时间值的文本表示。布局是预定义的常量值或引用日期时间:Mon Jan 2 15:04:05-0700 MST 2006 的特定格式。

Go 当前时间示例

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

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

Go 当前时间部分

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

current_time_parts.go
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 格式化当前时间

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

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

我们根据此特定引用日期时间的结构来格式化时间。

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

来源

Go time 包 - 参考

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

作者

我叫 Jan Bodnar,是一名充满激情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。到目前为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在教学编程方面拥有十多年的经验。

列出所有 Go 教程