Go (Golang) 中的日期处理:解析、格式化与操作库概览

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

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

开始课程

在 Go (Golang) 中处理日期:库与工具



Go 语言 (Golang) 提供了强大的标准库 time,它涵盖了大多数日期和时间处理任务。然而,对于复杂操作,例如解析非标准格式、处理相对日期或使用工作日历进行计算,社区创建了许多有用的库。在本文中,我们将探讨 Go 的内置功能以及用于日期处理的最佳第三方包。



1. 内置库 time



标准库 time 是 Go 中所有日期操作的基础。它提供:

  • 类型 Time、Duration、Location
  • 用于获取当前时间、创建日期、解析和格式化的函数
  • 对时区和单调时钟的支持


获取当前时间

package main

import ( "fmt" "time")

func main() { now := time.Now() fmt.Println("当前时间:", now) fmt.Println("年:", now.Year()) fmt.Println("月:", now.Month()) fmt.Println("日:", now.Day())}


日期格式化

Go 使用特殊的参考格式:Mon Jan 2 15:04:05 MST 2006(1,2,3,4,5,6 — 数字按升序排列)。

now := time.Now()fmt.Println(now.Format("2006-01-02 15:04:05"))   // 2025-03-15 14:30:00fmt.Println(now.Format("02 Jan 2006"))           // 15 Mar 2025fmt.Println(now.Format(time.RFC3339))            // 2025-03-15T14:30:00Z


字符串解析

dateStr := "2025-03-15 14:30:00"t, err := time.Parse("2006-01-02 15:04:05", dateStr)if err != nil {    panic(err)}fmt.Println(t) // 2025-03-15 14:30:00 +0000 UTC


时区处理

loc, _ := time.LoadLocation("Europe/Moscow")moscowTime := time.Now().In(loc)fmt.Println("莫斯科时间:", moscowTime.Format("15:04:05"))


2. 库 carbon



包 github.com/golang-module/carbon 是流行的 PHP 库 Carbon 的 Go 版本。它提供了便捷的日期处理 API,包括相对日期、人类可读格式和链式调用。



安装

go get github.com/golang-module/carbon/v2


使用示例

package main

import ( "fmt" "github.com/golang-module/carbon/v2")

func main() { // 当前日期 now := carbon.Now() fmt.Println(now.ToDateString()) // 2025-03-15

// 相对日期 fmt.Println(now.AddDays(7).ToDateString()) // 2025-03-22 fmt.Println(now.SubMonths(1).ToDateString()) // 2025-02-15 fmt.Println(now.StartOfMonth().ToDateString()) // 2025-03-01 fmt.Println(now.EndOfMonth().ToDateString()) // 2025-03-31

// 人类可读格式 fmt.Println(now.DiffForHumans()) // 刚刚

// 支持多种格式的解析 t := carbon.Parse("2025-03-15 14:30:00") fmt.Println(t.ToDateTimeString()) // 2025-03-15 14:30:00

// 时区处理 cst := carbon.Now(carbon.NewYork) fmt.Println(cst.ToDateTimeString()) // 纽约时间}


3. 库 now



包 github.com/jinzhu/now(来自 GORM 作者)提供了便捷的函数,用于获取时间段的开始和结束。



安装

go get github.com/jinzhu/now


示例

package main

import ( "fmt" "github.com/jinzhu/now" "time")

func main() { t := time.Now() fmt.Println(now.BeginningOfMonth(t)) // 2025-03-01 00:00:00 fmt.Println(now.EndOfMonth(t)) // 2025-03-31 23:59:59 fmt.Println(now.BeginningOfYear(t))

推荐