go 语言是一种新兴的编程语言,它的高效性和简洁性已经吸引了越来越多的开发者。在编写程序时,操作时间是一个常见的需求,因此 go 语言提供了许多与时间处理相关的函数。本文将介绍一些常用的时间处理函数。
- time.Now()
time.Now() 函数返回当前的时间。该函数返回的时间是一个 time.Time 类型的值。例如:
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println(now)
}输出:2021-08-20 11:12:48.693123 +0800 CST m=+0.000102671
- time.Parse()
time.Parse() 函数将一个字符串解析为一个 time.Time 类型的值。格式化字符串必须遵循特定的规则,以指示要解析的字符串所代表的时间。例如:
package main
import (
"fmt"
"time"
)
func main() {
layout := "2006-01-02 15:04:05"
str := "2021-08-20 10:10:10"
t, err := time.Parse(layout, str)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(t)
}
}输出:2021-08-20 10:10:10 +0000 UTC
- time.Unix()
time.Unix() 函数将 Unix 时间戳转换为一个 time.Time 类型的值。Unix 时间戳是自 1970 年 1 月 1 日 00:00:00 UTC 起经过的秒数。例如:
package main
import (
"fmt"
"time"
)
func main() {
unixTime := int64(1629488400)
t := time.Unix(unixTime, 0)
fmt.Println(t)
}输出:2021-08-20 10:20:00 +0000 UTC
- time.Duration()
time.Duration() 函数表示时间间隔,以纳秒为单位。时间间隔是一个 time.Duration 类型的值。例如:
package main
import (
"fmt"
"time"
)
func main() {
t1 := time.Now()
time.Sleep(time.Second)
t2 := time.Now()
duration := t2.Sub(t1)
fmt.Println(duration)
}输出:1.000743896s
- time.After()
time.After() 函数等待一段时间后返回一个 channel。该 channel 将在指定的时间后接收一个值。例如:
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("start")
<-time.After(time.Second * 3)
fmt.Println("end")
}输出:
start
end
以上就是关于 Go 语言中与时间处理相关的一些函数的介绍。在实际开发中,我们还需要根据具体需求使用其他的时间处理函数。在使用时,我们应该了解各个函数的作用和用法,以充分利用时间处理函数提高代码效率。










