首页 > 编程笔记 > Go语言笔记 阅读:7

Go语言time库获取时间的4种方法(附带实例)

在实际开发过程中,经常使用时间和日期工具。为此,Go 语言提供了 time 库,其中包含许多测量和显示时间的函数。

本节从 4 个方面讲解时间的获取,包括获取当前时间、获取时间戳、把时间戳转化为当前时间和获取当前是星期几。

Go语言time库获取当前时间

time 库的 Now() 函数可以获取当前时间。

【实例 1】使用 time 库的 Now() 函数获取本地的当前时间,并将其打印在控制台上;分别获取本地当前时间的年、月、日、小时、分钟和秒,并按“YYYY-mm-dd HH:MM:SS”格式把本地的当前时间打印在控制台上。代码如下:
package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now() // 获取当前时间
    fmt.Printf("本地当前时间: %v\n", now)

    year   := now.Year()      // 年
    month  := now.Month()     // 月
    day    := now.Day()       // 日
    hour   := now.Hour()      // 小时
    minute := now.Minute()    // 分钟
    second := now.Second()    // 秒

    fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}
运行结果如下:

本地当前时间: 2025-07-18 04:50:53.459623295 +0000 UTC m=+0.000093067
2025-07-18 04:50:53

Go语言time库获取时间戳

时间戳是指自 1970 年 1 月 1 日(08:00:00GMT)至本地当前时间的总毫秒数。time 库 Unix() 函数可以用于获取时间戳。

【实例 2】获取时间戳。使用 time 库的 Unix() 函数获取时间戳,并将时间戳打印在控制台上。代码如下:
package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()       // 获取当前时间
    timestamp := now.Unix() // 时间戳
    fmt.Printf("时间戳:%v\n", timestamp)
}
运行结果如下:

时间戳:1752814379

Go语言time库把时间戳转化为当前时间

使用 time.Unix() 函数将时间戳转为当前时间。代码如下:
package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()       // 获取当前时间
    timestamp := now.Unix() // 时间戳
    fmt.Printf("时间戳:%v\n", timestamp)

    timeNow := time.Unix(timestamp, 0) // 将时间戳转为当前时间
    fmt.Println(timeNow)
}
运行结果如下:

时间戳:1752814447
2025-07-18 04:54:07 +0000 UTC

Go语言time库获取当前是星期几

time 库的 Weekday() 函数可以获取当前日期是星期几。代码如下:
package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now() // 获取当前时间
    fmt.Println(t.Weekday().String())
}
运行结果如下:

Friday

相关文章