Go语言time包常用操作指南

向北走
向北走
发布时间:2026-10-15| 6人浏览过
原创

在Go语言开发中,正确且高效地处理时间是基础且关键的一环。本文详细梳理了 time 包的核心用法,从基础的时间获取到复杂的格式化、时间戳转换及差值计算,助力提升开发效率。

1. 获取当前时间

使用 time.Now() 函数可获取当前的本地时间,其返回值类型为 Time 结构体。该结构体是后续所有时间操作的基石。

package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	fmt.Println(now) // 输出示例: 2023-10-27 14:30:00 +0800 CST m=+0.000000001
}

2. 提取具体时间单位

通过 Time 结构体的方法,可以直接获取年、月、日、时、分、秒等具体数值,便于业务逻辑中的条件判断或展示。

package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	fmt.Printf("年份: %d\n", now.Year())       // 2023
	fmt.Printf("月份(数字): %d\n", int(now.Month())) // 10 (十月)
	fmt.Printf("日: %d\n", now.Day())          // 27
	fmt.Printf("小时: %d\n", now.Hour())        // 14
	fmt.Printf("分钟: %d\n", now.Minute())      // 30
	fmt.Printf("秒: %d\n", now.Second())        // 0
}

3. 时间格式化与解析

3.1 将时间转换为字符串

使用 Format(layout string) 方法。Go语言的引用时间为固定模板:2006-01-02 15:04:05(其中 1 代表一月,3 代表下午三点)。只需替换对应的连接符即可生成自定义格式的字符串。

package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	// 格式: YYYY-MM-DD HH:MM:SS
	fmt.Println(now.Format("2006-01-02 15:04:05"))
	// 格式: YYYY/MM/DD
	fmt.Println(now.Format("2006/01/02"))
}

3.2 将字符串解析为时间

使用 time.Parse(layout, value) 函数将符合特定格式的字符串转换为 Time 类型,返回时间与错误信息。

package main

import (
	"fmt"
	"time"
)

func main() {
	t, err := time.Parse("2006-01-02 15:04:05", "2023-10-27 14:30:00")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(t)
}

4. 时间戳操作

时间戳常用于数据库存储或序列化。Go提供了便捷的纳秒、微秒、毫秒及秒级时间戳方法。

  • Unix(): 返回秒级 Unix 时间戳。
  • UnixMilli(): 返回毫秒级 Unix 时间戳。
  • UnixMicro(): 返回微秒级 Unix 时间戳。
  • UnixNano(): 返回纳秒级 Unix 时间戳。
package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	fmt.Println("秒:", now.Unix())
	fmt.Println("毫秒:", now.UnixMilli())
	fmt.Println("纳秒:", now.UnixNano())
}

5. 创建指定时间

通过 time.Date(year, month, day, hour, min, sec, nsec, loc) 可构建精确的 Time 对象。

package main

import (
	"fmt"
	"time"
)

func main() {
	// 创建 2023-10-27 14:00:00 UTC时间
	date := time.Date(2023, 10, 27, 14, 0, 0, 0, time.UTC)
	fmt.Println(date)
}

6. 时间的加减与差值计算

Go 使用 Duration 类型来封装时间间隔,支持时、分、秒等单位的运算。

package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	
	// 增加一小时
	future := now.Add(time.Hour * 1)
	
	// 计算差值
	diff := future.Sub(now)
	fmt.Println("相差时间:", diff) // 输出: 1h0m0s
	
	// 判断先后关系
	fmt.Println("现在在指定时间前?", now.Before(future)) // true
	fmt.Println("现在在指定时间后?", now.After(future))  // false
}

小结

以上就是Go语言time包常用操作的详细内容,更多关于Golang时间处理技巧的资料请关注本站其它相关文章!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。