time 包常用函数速查
time 是 Go 标准库中处理时间的核心包:获取时间、格式化、解析、计时、定时、比较 都在这里。
核心分类(先记这个,函数全会)
| 分类 | 关键词 | 代表函数/类型 |
|---|---|---|
| 获取时间 | Now / Date | time.Now() / time.Date() |
| 时间戳 | Unix | Unix() / UnixMilli() / UnixMicro() |
| 格式化 | Format | Format() |
| 解析 | Parse | Parse() / ParseInLocation() |
| 时间运算 | Add / Sub | Add() / Sub() / AddDate() |
| 比较 | Before / After | Before() / After() / Equal() |
| 休眠 | Sleep | time.Sleep() |
| 定时器 | Timer / Ticker | NewTimer() / NewTicker() |
| 时区 | Location | LoadLocation() / FixedZone() |
| 常量 | Duration | Second / Minute / Hour |
获取当前时间 ⭐ 最常用
go
now := time.Now() // time.Time 类型
now.Year() // 2026
now.Month() // time.June
now.Day() // 12
now.Hour() // 14
now.Minute() // 30
now.Second() // 0
now.Nanosecond() // 纳秒
now.Weekday() // time.Friday
构造指定时间
go
t := time.Date(2026, 6, 12, 10, 30, 0, 0, time.Local)
时间戳 ⭐
go
now := time.Now()
now.Unix() // 秒级时间戳 1749717000
now.UnixMilli() // 毫秒 1749717000000
now.UnixMicro() // 微秒 1749717000000000
now.UnixNano() // 纳秒 1749717000000000000
// 时间戳 → time.Time
t1 := time.Unix(1749717000, 0) // 秒 + 纳秒
t2 := time.UnixMilli(1749717000000) // 毫秒(Go 1.17+)
t3 := time.UnixMicro(1749717000000000) // 微秒(Go 1.17+)
格式化 ⭐ 最常用
Go 的格式化不用 YYYY-MM-DD,而是用 参考时间 Mon Jan 2 15:04:05 MST 2006 记忆口诀:1 2 3 4 5 6 7(月 日 时 分 秒 年 时区)。
go
now := time.Now()
now.Format("2006-01-02 15:04:05") // "2026-06-12 14:30:00"
now.Format("2006-01-02") // "2026-06-12"
now.Format("15:04:05") // "14:30:00"
now.Format("2006/01/02 15:04") // "2026/06/12 14:30"
now.Format(time.RFC3339) // "2026-06-12T14:30:00+08:00"
内置常用布局常量
| 常量 | 输出 |
|---|---|
time.RFC3339 |
"2006-01-02T15:04:05Z07:00" |
time.RFC3339Nano |
"2006-01-02T15:04:05.999999999Z07:00" |
time.DateTime |
"2006-01-02 15:04:05" |
time.DateOnly |
"2006-01-02" |
time.TimeOnly |
"15:04:05" |
解析字符串 → time.Time ⭐
go
// Parse 默认 UTC 时区
t, err := time.Parse("2006-01-02 15:04:05", "2026-06-12 14:30:00")
// ParseInLocation 指定时区(推荐)⭐
loc, _ := time.LoadLocation("Asia/Shanghai")
t, err := time.ParseInLocation("2006-01-02 15:04:05", "2026-06-12 14:30:00", loc)
坑 :
Parse不传时区默认按 UTC 解析,导致东八区差 8 小时。用ParseInLocation可避免。
时间运算 ⭐
加减时间段(Duration)
go
now := time.Now()
later := now.Add(2 * time.Hour) // 2 小时后
before := now.Add(-30 * time.Minute) // 30 分钟前
加减年月日
go
now.AddDate(1, 2, 3) // +1年 +2月 +3天
now.AddDate(0, 0, -7) // 7 天前
now.AddDate(-1, 0, 0) // 1 年前
求时间差
go
diff := later.Sub(now) // time.Duration
diff.Hours() // 2.0
diff.Minutes() // 120.0
diff.Seconds() // 7200.0
diff.Milliseconds() // 7200000
时间比较 ⭐
go
t1 := time.Now()
t2 := t1.Add(time.Hour)
t1.Before(t2) // true t1 在 t2 之前?
t1.After(t2) // false t1 在 t2 之后?
t1.Equal(t2) // false 相等?(推荐,不受时区影响)
比较用
Equal()而非==,因为==对不同时区同一时刻会返回 false。
Duration 常量
go
time.Nanosecond // 1ns
time.Microsecond // 1μs
time.Millisecond // 1ms
time.Second // 1s
time.Minute // 1m
time.Hour // 1h
自由组合:3*time.Hour + 30*time.Minute → 3 小时 30 分钟。
休眠
go
time.Sleep(3 * time.Second) // 阻塞当前 goroutine 3 秒
time.Sleep(500 * time.Millisecond) // 500 毫秒
不要在主 goroutine 用
Sleep做定时任务,用Ticker代替。
定时器 Timer(一次性)
go
timer := time.NewTimer(5 * time.Second)
<-timer.C // 阻塞等待 5 秒到期
timer.Stop() // 取消(不再需要时务必 Stop,防止泄漏)
timer.Reset(3 * time.Second) // 重置为 3 秒
定时器 Ticker(周期性)⭐ 常用
go
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for range ticker.C {
fmt.Println("每 10 秒执行一次", time.Now().Format("15:04:05"))
}
时区处理 ⭐
go
// 加载时区(依赖系统 tzdata 或内嵌)
loc, err := time.LoadLocation("Asia/Shanghai")
loc, err := time.LoadLocation("America/New_York")
loc, err := time.LoadLocation("UTC")
// 固定偏移(东八区 = +8 小时)
loc := time.FixedZone("CST", 8*60*60)
// 转换时区
now := time.Now()
shanghaiTime := now.In(loc)
常见实战场景
获取今天零点
go
now := time.Now()
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
获取昨天 / 明天
go
yesterday := today.AddDate(0, 0, -1)
tomorrow := today.AddDate(0, 0, 1)
计算某月第一天和最后一天
go
firstDay := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
lastDay := firstDay.AddDate(0, 1, -1)
超时控制
go
select {
case result := <-doWork():
fmt.Println("完成:", result)
case <-time.After(5 * time.Second): // 5 秒超时
fmt.Println("超时")
}
time.After 内部创建 Timer,用完即弃,循环中请用 NewTimer + Reset 避免内存泄漏。
实战速记
go
// 当前时间戳
ts := time.Now().Unix()
// 格式化输出
time.Now().Format("2006-01-02 15:04:05")
// 解析字符串(务必指定时区)
t, _ := time.ParseInLocation("2006-01-02", "2026-06-12", time.Local)
// 计算耗时
start := time.Now()
doSomething()
fmt.Println("耗时:", time.Since(start)) // Since = Now().Sub(start)
// 距离未来某时刻还有多久
deadline := time.Date(2026, 12, 31, 0, 0, 0, 0, time.Local)
fmt.Println("剩余:", time.Until(deadline)) // Until = deadline.Sub(Now())
// 定时任务
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for range ticker.C { /* 每分钟执行 */ }
一句话记忆
Now()取时间,Format("2006-01-02 15:04:05")格式化,ParseInLocation解析别忘时区;
Add/Sub算差值,Before/After做比较,NewTicker做定时;时间布局记
1 2 3 4 5 6 7(月日时分秒年时区)。