全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-14 6 分钟 ✍️ juanwangdev

Go time包

Go标准库time提供时间和日期的表示、格式化、解析与计算。

时间获取

当前时间

Go
import "time"

// 获取当前时间
now := time.Now()

fmt.Println(now)        // 2026-05-14 10:30:45.123456789 +0800 CST
fmt.Println(now.Year())  // 2026
fmt.Println(now.Month()) // May
fmt.Println(now.Day())   // 14
fmt.Println(now.Hour())  // 10
fmt.Println(now.Minute()) // 30
fmt.Println(now.Second()) // 45

时间戳

Go
// Unix时间戳(秒)
timestamp := now.Unix()        // 1715675445

// Unix毫秒时间戳
millis := now.UnixMilli()      // 1715675445123

// Unix纳秒时间戳
nanos := now.UnixNano()        // 1715675445123456789

// 时间戳转时间
t := time.Unix(timestamp, 0)

时间格式化

Format方法

Go
now := time.Now()

// 格式化为字符串
s := now.Format("2006-01-02 15:04:05")
fmt.Println(s)  // 2026-05-14 10:30:45

// 自定义格式
s = now.Format("2006年01月02日")
fmt.Println(s)  // 2026年05月14日

Go使用固定参考时间2006-01-02 15:04:05作为格式模板。

常用格式

Go
// 标准格式
now.Format("2006-01-02")           // 日期
now.Format("15:04:05")             // 时间
now.Format("2006-01-02 15:04:05")  // 日期时间

// RFC3339格式
now.Format(time.RFC3339)           // 2026-05-14T10:30:45+08:00

时间解析

Parse函数

Go
// 字符串解析为时间
t, err := time.Parse("2006-01-02", "2026-05-14")
if err != nil {
    log.Fatal(err)
}
fmt.Println(t.Year())  // 2026

ParseInLocation

Go
// 指定时区解析
loc, _ := time.LoadLocation("Asia/Shanghai")
t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2026-05-14 10:30:45", loc)

格式占位符表

占位符含义示例
20062026
0105
0214
15时(24小时制)10
0430
0545
PMAM/PM标记PM
.000毫秒.123
-0700时区+0800

时间计算

Duration类型

Go
// Duration表示时间间隔
d := time.Hour          // 1小时
d = time.Minute         // 1分钟
d = time.Second         // 1秒
d = time.Millisecond    // 1毫秒

// 自定义Duration
d = 5 * time.Minute     // 5分钟
d = 100 * time.Millisecond // 100毫秒

Add方法

Go
now := time.Now()

// 加时间
t := now.Add(1 * time.Hour)     // 1小时后
t = now.Add(-30 * time.Minute)  // 30分钟前
t = now.Add(24 * time.Hour)     // 明天

fmt.Println(t)

Sub方法

Go
// 时间差
start := time.Now()
// ... 执行操作
end := time.Now()

duration := end.Sub(start)
fmt.Println(duration)         // 5.123s
fmt.Println(duration.Seconds()) // 5.123秒

时间比较

Before/After/Equal

Go
t1 := time.Now()
t2 := t1.Add(1 * time.Hour)

// 比较
fmt.Println(t1.Before(t2))  // true
fmt.Println(t1.After(t2))   // false
fmt.Println(t1.Equal(t2))   // false

时间睡眠

time.Sleep

Go
// 程序暂停
time.Sleep(1 * time.Second)  // 等待1秒
time.Sleep(100 * time.Millisecond) // 等待100毫秒

定时器

time.Timer

Go
// 创建定时器
timer := time.NewTimer(2 * time.Second)

// 等待定时器触发
<-timer.C
fmt.Println("Timer expired")

// 停止定时器
timer.Stop()

// 重置定时器
timer.Reset(1 * time.Second)

time.After

Go
// 单次触发(返回channel)
select {
case <-time.After(5 * time.Second):
    fmt.Println("Timeout")
case msg := <-ch:
    fmt.Println(msg)
}

周期定时器

time.Ticker

Go
// 创建周期定时器
ticker := time.NewTicker(1 * time.Second)

for t := range ticker.C {
    fmt.Println(t)  // 每秒打印一次
}

// 停止定时器
ticker.Stop()

time.Tick

Go
// 简化周期定时(无法停止)
for range time.Tick(1 * time.Second) {
    fmt.Println("Tick")
}

time.Tick无法停止,生产环境推荐使用NewTicker。

时区处理

LoadLocation

Go
// 加载时区
loc, _ := time.LoadLocation("America/New_York")
loc, _ = time.LoadLocation("Asia/Shanghai")
loc, _ = time.LoadLocation("UTC")

// 创建指定时区时间
t := time.Date(2026, 5, 14, 10, 30, 0, 0, loc)

// 转换时区
t = t.In(time.UTC)

时间构造

time.Date

Go
// 构造时间
t := time.Date(2026, 5, 14, 10, 30, 0, 0, time.Local)

fmt.Println(t.Year())   // 2026
fmt.Println(t.Month())  // May
fmt.Println(t.Day())    // 14

Duration转换方法

方法返回值
Seconds()float64秒
Milliseconds()float64毫秒
Microseconds()float64微秒
Nanoseconds()int64纳秒
Minutes()float64分钟
Hours()float64小时

要点总结

  • time.Now()获取当前时间
  • Format使用2006-01-02模板格式化
  • Parse解析字符串为时间
  • Unix()/UnixNano()获取时间戳
  • Add/Sub计算时间加减
  • Before/After/Equal比较时间
  • time.Sleep暂停程序
  • Timer单次定时,Ticker周期定时
  • Duration表示时间间隔
  • LoadLocation处理时区

📝 发现内容有误?点击此处直接编辑

← 上一篇 Go strings包
下一篇 → Go垃圾回收机制
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库