主题
time 包常用操作
1. 获取当前时间
go
now := time.Now()
fmt.Println("Current time:", now)
2. 时间格式化
使用 Format
方法,Go 使用特定时间模板:
go
formatted := now.Format("2006-01-02 15:04:05")
fmt.Println("Formatted time:", formatted)
3. 时间解析
使用 Parse
方法将字符串解析为时间:
go
t, err := time.Parse("2006-01-02", "2025-05-22")
if err == nil {
fmt.Println("Parsed time:", t)
}
4. 时间运算
go
tomorrow := now.Add(24 * time.Hour)
duration := tomorrow.Sub(now)
fmt.Println("Duration:", duration)
time 包是处理时间和日期的基础工具,支持丰富的时间操作。