Golang 时间和日期相关函数,Golang面试问项目难点
warning:
这篇文章距离上次修改已过436天,其中的内容可能已经有所变动。
在Golang中,时间和日期可以通过标准库time来处理。以下是一些常用的函数和操作:
time.Now(): 获取当前时间。time.Since(t Time): 获取从t到现在的时间间隔。time.Unix(sec, nsec int64): 根据秒和纳秒创建一个时间。time.Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location): 根据指定的日期和时间创建一个时间。t.Add(d Duration): 给时间t加上一个时间段d。t.Sub(u Time): 获取t和u之间的时间差。t.Format(layout string): 根据指定的layout格式化时间t。time.Parse(layout, value string) (Time, error): 根据指定的layout解析字符串value到时间。time.Sleep(d Duration): 使当前goroutine暂停执行指定的时间段。
以下是一些示例代码:
package main
import (
"fmt"
"time"
)
func main() {
// 获取当前时间
now := time.Now()
fmt.Println("Current Time:", now)
// 获取两个时间点之间的差异
then := now.Add(-10 * time.Minute)
elapsed := now.Sub(then)
fmt.Printf("Time elapsed since 10 minutes ago: %s\n", elapsed)
// 创建一个特定时间
specificTime := time.Date(2023, time.April, 10, 12, 0, 0, 0, time.UTC)
fmt.Println("Specific Time:", specificTime)
// 时间格式化和解析
formatted := now.Format("2006-01-02 15:04:05")
fmt.Println("Formatted Time:", formatted)
parsed, err := time.Parse("2006-01-02 15:04:05", formatted)
if err != nil {
fmt.Println(err)
} else {
fmt.Println("Parsed Time:", parsed)
}
// 暂停执行
time.Sleep(5 * time.Second)
fmt.Println("After sleeping for 5 seconds")
}这段代码展示了如何在Go中使用time包来处理时间和日期,包括创建、比较、格式化和解析时间。
评论已关闭