Go 标准库 —— time 常用类型和方法

简介:

time 包提供了时间的显示和测量用的函数,日历的计算采用的是公历

本文仅整理演示常用的类型和方法,完整的可参考标准库文档

原文地址: https://shockerli.net/post/golang-pkg-time/

type Location

Location 代表一个(关联到某个时间点的)地点,以及该地点所在的时区

func LoadLocation

func LoadLocation(name string) (*Location, error)

LoadLocation 返回使用给定的名字创建的 Location

type Time

Time 代表一个纳秒精度的时间点

func Now

func Now() Time

Now 返回当前本地时间

func Parse

func Parse(layout, value string) (Time, error)

Parse 解析一个格式化的时间字符串并返回它代表的时间。
layout 定义输入的时间格式,value 的时间格式需与 layout 保持一致

Example:

t, _ := time.Parse("2006-01-02", "2018-05-31")
fmt.Println(t)

// 输出:
// 2018-05-31 00:00:00 +0000 UTC

func ParseInLocation

func ParseInLocation(layout, value string, loc *Location) (Time, error)

ParseInLocation 功能与 Parse 类似,但有两个重要的不同之处:
第一,当缺少时区信息时,Parse 将时间解释为 UTC 时间,而 ParseInLocation 将返回值的 Location 设置为 loc;
第二,当时间字符串提供了时区偏移量信息时,Parse 会尝试去匹配本地时区,而 ParseInLocation 会去匹配 loc。

Example:

loc, _ := time.LoadLocation("PRC")
t, _ := time.ParseInLocation("2006-01-02", "2018-05-31", loc)
fmt.Println(t)

// 输出:
// 2018-05-31 00:00:00 +0800 CST

func (Time) Location

func (t Time) Location() *Location

Location 返回 t 的地点和时区信息

Example:

loc, _ := time.LoadLocation("PRC")
t, _ := time.ParseInLocation("2006-01-02", "2018-05-31", loc)
fmt.Println(t.Location())

// 输出:
// PRC

func (Time) Unix

func (t Time) Unix() int64

Unix 将 t 表示为 Unix 时间,即从时间点January 1, 1970 UTC到时间点 t 所经过的时间(单位:秒)

func (Time) Format

func (t Time) Format(layout string) string

Format 根据 layout 指定的格式返回 t 代表的时间点的格式化文本表示。layout 定义了参考时间:

Mon Jan 2 15:04:05 -0700 MST 2006

格式化后的字符串表示,它作为期望输出的例子。同样的格式规则会被用于格式化时间。

Example:

loc, _ := time.LoadLocation("PRC")
t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2018-05-31 09:22:19", loc)
fmt.Println(t)
fmt.Println(t.Format("2006-01-02 15:04:05"))

// 输出:
// 2018-05-31 09:22:19 +0800 CST
// 2018-05-31 09:22:19

func (Time) String

func (t Time) String() string

String 返回采用如下格式字符串的格式化时间:

"2006-01-02 15:04:05.999999999 -0700 MST"

type Duration

Duration 类型代表两个时间点之间经过的时间,以纳秒为单位。可表示的最长时间段大约290年。

常用的时间段:

const (
    Nanosecond  Duration = 1
    Microsecond          = 1000 * Nanosecond
    Millisecond          = 1000 * Microsecond
    Second               = 1000 * Millisecond
    Minute               = 60 * Second
    Hour                 = 60 * Minute
)

Example:
要将整数个某时间单元表示为 Duration 类型值,用乘法:

seconds := 100000
fmt.Println(time.Duration(seconds) * time.Second)

// 输出:
// 27h46m40s

type Timer

type Timer struct {
    C <-chan Time
    // 内含隐藏或非导出字段
}

Timer 类型代表单次时间事件。当 Timer 到期时,当时的时间会被发送给 C,除非 Timer 是被 AfterFunc 函数创建的。

func NewTimer

func NewTimer(d Duration) *Timer

NewTimer 创建一个 Timer,它会在最少过去时间段 d 后到期,向其自身的 C 字段发送当时的时间。

Example:

fmt.Println(time.Now())

timer := time.NewTimer(time.Second * 2)

<-timer.C

fmt.Println(time.Now())

// 输出:
// 2018-06-04 12:55:32.426676958 +0800 CST m=+0.000332587
// 2018-06-04 12:55:34.42745008 +0800 CST m=+2.001045690

func AfterFunc

func AfterFunc(d Duration, f func()) *Timer

AfterFunc 另起一个 go 协程等待时间段 d 过去,然后调用 f。它返回一个 Timer,可以通过调用其 Stop 方法来取消等待和对 f 的调用。

wait := sync.WaitGroup{}
fmt.Println("start", time.Now())

wait.Add(1)

timer := time.AfterFunc(time.Second * 3, func() {
    fmt.Println("get timer", time.Now())
    wait.Done()
})

time.Sleep(time.Second)
fmt.Println("sleep", time.Now())

timer.Reset(time.Second * 2)

wait.Wait()

// 输出:
// start 2018-06-04 13:11:25.478294853 +0800 CST m=+0.000332881
// sleep 2018-06-04 13:11:26.480826469 +0800 CST m=+1.002156500
// get timer 2018-06-04 13:11:28.483455973 +0800 CST m=+3.003496118

func (*Timer) Reset

func (t *Timer) Reset(d Duration) bool

Reset 使 t 重新开始计时,(本方法返回后再)等待时间段 d 过去后到期。如果调用时 t 还在等待中会返回真;如果 t 已经到期或者被停止了会返回假。

wait := sync.WaitGroup{}
fmt.Println("start", time.Now())

wait.Add(1)
timer := time.NewTimer(time.Second * 2)

go func() {
    <-timer.C

    fmt.Println("get timer", time.Now())
    wait.Done()
}()

time.Sleep(time.Second)
fmt.Println("sleep", time.Now())

timer.Reset(time.Second * 3)

wait.Wait()

// 输出:
// start 2018-06-04 13:07:51.780367114 +0800 CST m=+0.000324036
// sleep 2018-06-04 13:07:52.783389811 +0800 CST m=+1.003316644
// get timer 2018-06-04 13:07:55.784534298 +0800 CST m=+4.004371103

func (*Timer) Stop

func (t *Timer) Stop() bool

Stop 停止 Timer 的执行。如果停止了 t 会返回真;如果 t 已经被停止或者过期了会返回假。Stop 不会关闭通道 t.C,以避免从该通道的读取不正确的成功。

Example:

fmt.Println("start")

timer := time.NewTimer(time.Second * 2)

go func() {
    <-timer.C

    fmt.Println("get timer")
}()

if timer.Stop() {
    fmt.Println("timer stoped")
}

// 输出:
// start
// timer stoped

type Ticker

type Ticker struct {
    C <-chan Time // 周期性传递时间信息的通道
    // 内含隐藏或非导出字段
}

Ticker 保管一个通道,并每隔一段时间向其传递"tick"。

func NewTicker

func NewTicker(d Duration) *Ticker

NewTicker 返回一个新的 Ticker,该 Ticker 包含一个通道字段,并会每隔时间段 d 就向该通道发送当时的时间。它会调整时间间隔或者丢弃 tick 信息以适应反应慢的接收者。如果d <= 0会触发panic。关闭该 Ticker 可以释放相关资源。

Example:

fmt.Println("start", time.Now())

ticker := time.NewTicker(time.Second)

go func() {
    for tick := range ticker.C {
        fmt.Println("tick at", tick)
    }
}()

time.Sleep(time.Second * 5)
ticker.Stop()

fmt.Println("stoped", time.Now())

// 输出: 
// start 2018-06-04 13:21:20.443700752 +0800 CST m=+0.000376994
// tick at 2018-06-04 13:21:21.448276294 +0800 CST m=+1.004922401
// tick at 2018-06-04 13:21:22.44666211 +0800 CST m=+2.003278267
// tick at 2018-06-04 13:21:23.446749266 +0800 CST m=+3.003335423
// tick at 2018-06-04 13:21:24.445154097 +0800 CST m=+4.001710303
// stoped 2018-06-04 13:21:25.445239727 +0800 CST m=+5.001765933

func Sleep

func Sleep(d Duration)

Sleep 阻塞当前 go 协程至少 d 时间段。d <= 0时,Sleep 会立刻返回。

func After

func After(d Duration) <-chan Time

After 会在另一线程经过时间段 d 后向返回值发送当时的时间。等价于NewTimer(d).C

Example:

fmt.Println("start", time.Now())

timer := time.After(time.Second)

select {
case t := <-timer:
    fmt.Println("get timer", t)
}

fmt.Println("stoped", time.Now())

// 输出:
// start 2018-06-04 13:35:23.367586344 +0800 CST m=+0.000370476
// get timer 2018-06-04 13:35:24.368447041 +0800 CST m=+1.001201148
// stoped 2018-06-04 13:35:24.368787684 +0800 CST m=+1.001541781

func Tick

func Tick(d Duration) <-chan Time

Tick 是 NewTicker 的封装,只提供对 Ticker 的通道的访问。如果不需要关闭 Ticker,本函数就很方便。

Example:

fmt.Println("start", time.Now())

count := 0
wait := sync.WaitGroup{}
wait.Add(1)
ticker := time.Tick(time.Second)

go func() {
    for tick := range ticker {
        count += 1
        fmt.Println("tick at", tick)

        if count >= 5 {
            wait.Done()
            break
        }
    }
}()

wait.Wait()

fmt.Println("stoped", time.Now())

// 输出:
// start 2018-06-04 13:30:56.49323192 +0800 CST m=+0.000306375
// tick at 2018-06-04 13:30:57.493468434 +0800 CST m=+1.000512884
// tick at 2018-06-04 13:30:58.493509786 +0800 CST m=+2.000524236
// tick at 2018-06-04 13:30:59.494584076 +0800 CST m=+3.001568495
// tick at 2018-06-04 13:31:00.494248484 +0800 CST m=+4.001202915
// tick at 2018-06-04 13:31:01.498742563 +0800 CST m=+5.005666860
// stoped 2018-06-04 13:31:01.499025155 +0800 CST m=+5.005949444

原文地址: https://shockerli.net/post/golang-pkg-time/


目录
相关文章
|
3月前
|
JSON Go 开发者
go-carbon v2.5.0 发布,轻量级、语义化、对开发者友好的 golang 时间处理库
carbon 是一个轻量级、语义化、对开发者友好的 Golang 时间处理库,提供了对时间穿越、时间差值、时间极值、时间判断、星座、星座、农历、儒略日 / 简化儒略日、波斯历 / 伊朗历的支持。
59 4
|
3月前
|
JSON 前端开发 JavaScript
聊聊 Go 语言中的 JSON 序列化与 js 前端交互类型失真问题
在Web开发中,后端与前端的数据交换常使用JSON格式,但JavaScript的数字类型仅能安全处理-2^53到2^53间的整数,超出此范围会导致精度丢失。本文通过Go语言的`encoding/json`包,介绍如何通过将大整数以字符串形式序列化和反序列化,有效解决这一问题,确保前后端数据交换的准确性。
68 4
|
3月前
|
存储 Cloud Native Shell
go库介绍:Golang中的Viper库
Viper 是 Golang 中的一个强大配置管理库,支持环境变量、命令行参数、远程配置等多种配置来源。本文详细介绍了 Viper 的核心特点、应用场景及使用方法,并通过示例展示了其强大功能。无论是简单的 CLI 工具还是复杂的分布式系统,Viper 都能提供优雅的配置管理方案。
|
3月前
|
Go
go语言常量的类型
【10月更文挑战第20天】
32 2
|
3月前
|
JSON 安全 网络协议
go语言使用内置函数和标准库
【10月更文挑战第18天】
25 3
|
3月前
|
JSON 监控 安全
go语言选择合适的工具和库
【10月更文挑战第17天】
22 2
|
3月前
|
存储 Go PHP
Go语言中的加解密利器:go-crypto库全解析
在软件开发中,数据安全和隐私保护至关重要。`go-crypto` 是一个专为 Golang 设计的加密解密工具库,支持 AES 和 RSA 等加密算法,帮助开发者轻松实现数据的加密和解密,保障数据传输和存储的安全性。本文将详细介绍 `go-crypto` 的安装、特性及应用实例。
163 0
|
4月前
|
SQL 关系型数据库 MySQL
Go语言项目高效对接SQL数据库:实践技巧与方法
在Go语言项目中,与SQL数据库进行对接是一项基础且重要的任务
122 11
|
2月前
|
存储 监控 算法
员工上网行为监控中的Go语言算法:布隆过滤器的应用
在信息化高速发展的时代,企业上网行为监管至关重要。布隆过滤器作为一种高效、节省空间的概率性数据结构,适用于大规模URL查询与匹配,是实现精准上网行为管理的理想选择。本文探讨了布隆过滤器的原理及其优缺点,并展示了如何使用Go语言实现该算法,以提升企业网络管理效率和安全性。尽管存在误报等局限性,但合理配置下,布隆过滤器为企业提供了经济有效的解决方案。
85 8
员工上网行为监控中的Go语言算法:布隆过滤器的应用
|
2月前
|
Go 开发工具
百炼-千问模型通过openai接口构建assistant 等 go语言
由于阿里百炼平台通义千问大模型没有完善的go语言兼容openapi示例,并且官方答复assistant是不兼容openapi sdk的。 实际使用中发现是能够支持的,所以自己写了一个demo test示例,给大家做一个参考。