Post

Day13(Time)

时间包

时间包 time 提供了日期和时间相关的函数和结构体。使用这个包可以完成时间格式化、时间比较、定时器等功能

获取当前时间

1
2
now := time.Now()
fmt.Println(now)

时间格式化输出

1
2
t := time.Now()
fmt.Println(t.Format("2006-01-02 15:04:05"))

时间比较

1
2
3
4
5
t1 := time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)
t2 := time.Date(2022, 1, 1, 0, 0, 0, 0, time.UTC)
if t1.Before(t2) {
    fmt.Println("t1 is before t2")
}

定时器

1
2
3
4
5
6
7
8
9
ticker := time.NewTicker(1 * time.Second)
go func() {
    for t := range ticker.C {
        fmt.Println("Tick at", t)
    }
}()
time.Sleep(5 * time.Second)
ticker.Stop()
fmt.Println("Ticker stopped")

以上代码使用了 NewTicker 创建了一个 1 秒钟的定时器,然后在一个单独的 goroutine 中,使用 range 遍历了这个定时器,并在定时器到期时输出当前时间。主 goroutine 中使用 Sleep 让程序等待 5 秒钟,然后使用 Stop 停止定时器。 时间包 time 还有很多其他的用法,例如定时任务、时区转换等。在 Golang 开发中,经常需要用到时间相关的操作,因此熟悉时间包的使用是很重要的。

This post is licensed under CC BY 4.0 by the author.