Go语言日期与时间处理完全指南

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

在 Go 中处理日期和时间:从基础到高级技术

Go 编程语言(Golang)提供了强大且直观的 time 包来处理日期和时间。与许多其他语言不同,Go 使用基于参考日期(Mon Jan 2 15:04:05 MST 2006)的独特格式化方法。在本文中,我们将详细解析所有关键方面:从创建时间对象到处理定时器和时区。无论您是初学者还是正在转向 Go 的经验丰富的开发者,本文都将为您提供帮助。



1. 基础:创建、获取和输出时间

核心类型是 time.Time。使用 time.Now() 可以获取当前时刻。使用 time.Date() 可以创建特定日期。



package main

import ( "fmt" "time")

func main() { // 当前时间 now := time.Now() fmt.Println("现在:", now)

// 创建特定日期(年、月、日、时、分、秒、纳秒、Location) specific := time.Date(2025, time.January, 15, 10, 30, 0, 0, time.UTC) fmt.Println("特定日期:", specific)

// 提取组件 fmt.Println("年:", now.Year()) fmt.Println("月:", now.Month()) fmt.Println("日:", now.Day()) fmt.Println("时:", now.Hour()) fmt.Println("分:", now.Minute()) fmt.Println("秒:", now.Second()) fmt.Println("星期几:", now.Weekday())}


程序输出将显示当前时间及其组件。请注意:time.Now() 返回系统本地时区的时间。



2. 格式化和解析:Go 的独特特性

在 Go 中,日期格式化不是通过 YYYY-MM-DD 这样的字符,而是通过 参考日期:Mon Jan 2 15:04:05 MST 2006(或 01/02 03:04:05PM '06 -0700)。记住这个神奇字符串——它看起来像 1 2 3 4 5 6 -7。



  • 1 — 月(01, Jan, January)
  • 2 — 日(02, 2)
  • 3 — 12 小时制的小时(03, 3)
  • 4 — 分(04, 4)
  • 5 — 秒(05, 5)
  • 6 — 年(06, 2006)
  • -7 — 时区(MST, -0700, -07:00)


格式化(Time → String)

now := time.Now()

// 标准格式fmt.Println(now.Format("2006-01-02 15:04:05")) // 2025-01-15 10:30:45fmt.Println(now.Format("02.01.2006")) // 15.01.2025fmt.Println(now.Format(time.RFC3339)) // 2025-01-15T10:30:45Zfmt.Println(now.Format("Mon, 02 Jan 2006 15:04:05 MST")) // Wed, 15 Jan 2025 10:30:45 UTC


解析(String → Time)

// 将字符串解析为 time.TimedateStr := "2025-01-15 10:30:45"layout := "2006-01-02 15:04:05"parsedTime, err := time.Parse(layout, dateStr)if err != nil {    panic(err)}fmt.Println("已解析:", parsedTime)

// 带时区的解析dateWithZone := "2025-01-15T10:30:45+03:00"parsedWithZone, _ := time.Parse(time.RFC3339, dateWithZone)fmt.Println("带时区:", parsedWithZone)


如果您需要在特定时区解析日期,请使用 time.ParseInLocation()。



3. 日期运算:Duration、Add、Sub 和比较

time.Duration 类型表示时间间隔。Go 提供了常量:Nanosecond、Microsecond、Millisecond、Second、Minute、Hour。



now := time.Now()

// 添加时间future := now.Add(72 * time.Hour) // +3 天fmt.Println("72 小时后:", future)

// 减去时间past := now.Add(-30 * time.Minute) // 30 分钟前fmt.P

博客

书籍推荐