以下是 Go 语言 time
模块的详细说明及示例,涵盖时间操作、定时器、时区处理等核心功能:
一、时间基础操作
1. 获取时间
// 当前本地时间
now := time.Now()
fmt.Println(now) // 2023-08-04 15:30:45.123456 +0800 CST// 构造指定时间
t := time.Date(2023, 8, 4, 12, 30, 0, 0, time.UTC)
fmt.Println(t) // 2023-08-04 12:30:00 +0000 UTC
2. 时间戳转换
// 获取秒级/毫秒级/纳秒级时间戳
sec := now.Unix() // 1691134245
msec := now.UnixMilli()// 1691134245123
nsec := now.UnixNano() // 1691134245123456789// 时间戳转Time对象
t1 := time.Unix(sec, 0) // 2023-08-04 15:30:45 +0800 CST
二、时间格式化与解析
1. 标准格式化
// 格式化为字符串(固定布局)
fmt.Println(now.Format("2006-01-02 15:04:05")) // 2023-08-04 15:30:45
fmt.Println(now.Format(time.RFC3339)) // 2023-08-04T15:30:45+08:00// 解析时间字符串
t2, _ := time.Parse("2006-01-02", "2023-08-04")
fmt.Println(t2) // 2023-08-04 00:00:00 +0000 UTC
2. 时区处理
// 加载时区
loc, _ := time.LoadLocation("America/New_York")
nyTime := now.In(loc)
fmt.Println(nyTime) // 2023-08-04 03:30:45 -0400 EDT// 创建固定时区
fixedZone := time.FixedZone("CST", 8*3600)
t3 := time.Date(2023, 8, 4, 12, 0, 0, 0, fixedZone)
三、时间运算与比较
1. 时间加减
// 加1小时30分钟
t4 := now.Add(1*time.Hour + 30*time.Minute)// 计算时间差
duration := t4.Sub(now) // 1h30m0s// 使用时间常量
t5 := now.Add(24 * time.Hour) // 加1天
2. 时间比较
// 判断时间先后
isAfter := now.After(t3) // true
isBefore := now.Before(t3) // false// 计算相对时间
time.Since(t3) // 已过时间
time.Until(t3) // 剩余时间
四、定时器与周期任务
1. Timer(单次定时)
timer := time.NewTimer(2 * time.Second)
<-timer.C // 阻塞等待2秒
timer.Stop() // 取消未触发的定时器
2. Ticker(周期触发)
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()for {select {case <-ticker.C:fmt.Println("每秒触发")case <-time.After(5 * time.Second):return // 5秒后退出}
}
五、其他实用方法
1. 睡眠控制
time.Sleep(100 * time.Millisecond) // 精确睡眠
2. 时间间隔计算
start := time.Now()
// 执行某些操作...
elapsed := time.Since(start) // 计算耗时
fmt.Printf("耗时: %v\n", elapsed)
3. 时间组成部分提取
year := now.Year() // 2023
month := now.Month() // August
day := now.Day() // 4
hour := now.Hour() // 15
minute := now.Minute() // 30
4. 时间周期判断
// 判断是否为周末
if now.Weekday() == time.Saturday || now.Weekday() == time.Sunday {fmt.Println("周末")
}
六、特殊时间处理
1. 截止时间控制
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()select {
case <-ctx.Done():fmt.Println("操作超时")
}
2. 解析持续时间字符串
duration, _ := time.ParseDuration("1h30m40s")
fmt.Println(duration.Hours()) // 1.511111111111111
七、时间格式布局对照表
布局字符 | 含义 | 示例 |
---|---|---|
2006 | 年(4位) | 2023 |
01 | 月(前导零) | 08 |
02 | 日(前导零) | 04 |
15 | 时(24小时制) | 15 |
04 | 分(前导零) | 05 |
05 | 秒(前导零) | 06 |
.999 | 毫秒(可重复) | .123 |
MST | 时区缩写 | CST |
-0700 | 时区偏移 | +0800 |
八、典型应用场景
1. 接口超时控制
func fetchData() (string, error) {// 模拟网络请求time.Sleep(2 * time.Second)return "data", nil
}func main() {ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)defer cancel()select {case result := <-asyncFetch(ctx):fmt.Println(result)case <-ctx.Done():fmt.Println("请求超时")}
}
2. 定时批处理
func batchJob() {ticker := time.NewTicker(5 * time.Minute)for range ticker.C {fmt.Println("执行定时任务:", time.Now().Format("15:04:05"))}
}
time
包是 Go 语言时间处理的基石,熟练掌握其 API 可以高效处理各种时间相关需求。建议结合官方文档 (pkg.go.dev/time) 进行深入理解。