Skip to content

go std time

Go 标准库中的 time 包提供了对日期和时间的支持,包括获取当前时间、格式化和解析时间、定时器、计时器、时间区间的计算等功能。它是 Go 语言中处理时间和日期操作的核心库。下面详细介绍 time 包的主要功能及常见用法。

1. 获取当前时间

可以使用 time.Now() 来获取当前本地时间,它返回一个 time.Time 类型的值。

go
package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	fmt.Println("Current time:", now)
}

2. 时间格式化

Go 使用自定义时间格式来格式化和解析时间。格式化字符串使用 Go 固定的参考时间 Mon Jan 2 15:04:05 PST 2006,这个时间字符串用于指定格式。

格式化时间

go
package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()

	// 格式化为 "年-月-日 时:分:秒"
	fmt.Println("Formatted time:", now.Format("2006-01-02 15:04:05"))

	// 格式化为 "日/月/年"
	fmt.Println("Formatted time:", now.Format("02/01/2006"))
}

参考时间说明:

  • 2006 - 年
  • 01 - 月(两位)
  • 02 - 日(两位)
  • 15 - 小时(24小时制)
  • 04 - 分钟
  • 05 - 秒
  • PM - 显示 AM/PM
  • Mon - 星期几(英文缩写)
  • Jan - 月份(英文缩写)
  • MST - 时区(例如 UTC)

3. 解析时间

time.Parse() 可以将字符串解析为 time.Time 对象。解析时使用相同的参考时间格式。

go
package main

import (
	"fmt"
	"time"
)

func main() {
	layout := "2006-01-02 15:04:05"
	str := "2024-12-23 18:30:00"
	parsedTime, err := time.Parse(layout, str)
	if err != nil {
		fmt.Println("Error parsing time:", err)
		return
	}
	fmt.Println("Parsed time:", parsedTime)
}

4. 时间戳(Unix 时间戳)

Unix 时间戳是指自 1970 年 1 月 1 日(UTC)以来的秒数或毫秒数。time 包提供了与时间戳相关的函数。

获取当前 Unix 时间戳(秒和毫秒)

go
package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()

	// 获取 Unix 时间戳(秒)
	fmt.Println("Unix timestamp (seconds):", now.Unix())

	// 获取 Unix 时间戳(毫秒)
	fmt.Println("Unix timestamp (milliseconds):", now.UnixMilli())

	// 获取 Unix 时间戳(纳秒)
	fmt.Println("Unix timestamp (nanoseconds):", now.UnixNano())
}

将时间戳转换为 time.Time

go
package main

import (
	"fmt"
	"time"
)

func main() {
	// Unix 时间戳(秒)
	timestamp := int64(1672531199)

	// 转换为 time.Time 类型
	t := time.Unix(timestamp, 0)
	fmt.Println("Time from Unix timestamp:", t)
}

5. 时间间隔(Duration)

time.Duration 类型表示两个时间点之间的间隔,它是以纳秒为单位的整数。你可以通过各种常量(如 time.Second, time.Minute 等)来指定时间间隔。

创建和使用 Duration

go
package main

import (
	"fmt"
	"time"
)

func main() {
	duration := 2 * time.Hour + 30 * time.Minute
	fmt.Println("Duration:", duration)

	// 时间加减操作
	now := time.Now()
	newTime := now.Add(duration)
	fmt.Println("New time after adding duration:", newTime)

	// 从当前时间减去 duration
	earlierTime := now.Add(-duration)
	fmt.Println("New time after subtracting duration:", earlierTime)
}

6. 定时器和计时器

Go 提供了 time.Timertime.Ticker 来实现定时器和周期性任务。

定时器(一次性延时)

定时器会在指定的时间后执行某个操作。

go
package main

import (
	"fmt"
	"time"
)

func main() {
	// 创建一个定时器,指定时间后触发
	timer := time.NewTimer(3 * time.Second)

	// 阻塞直到定时器到期
	<-timer.C
	fmt.Println("Timer expired!")
}

计时器(周期性任务)

计时器会按照指定的间隔周期性地触发。

go
package main

import (
	"fmt"
	"time"
)

func main() {
	// 每隔 1 秒触发一次
	ticker := time.NewTicker(1 * time.Second)

	// 触发 5 次后停止
	for i := 0; i < 5; i++ {
		<-ticker.C
		fmt.Println("Ticker ticked")
	}

	// 停止计时器
	ticker.Stop()
	fmt.Println("Ticker stopped")
}

7. 时间的比较和计算

你可以比较两个 time.Time 对象,并执行加减等操作。

比较时间

go
package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	anotherTime := now.Add(1 * time.Hour)

	// 比较两个时间
	fmt.Println("now is before anotherTime:", now.Before(anotherTime))
	fmt.Println("now is after anotherTime:", now.After(anotherTime))
	fmt.Println("now is equal to anotherTime:", now.Equal(anotherTime))
}

时间加减

go
package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()

	// 时间加减操作
	oneDayLater := now.Add(24 * time.Hour)
	oneMonthEarlier := now.AddDate(0, -1, 0)

	fmt.Println("One day later:", oneDayLater)
	fmt.Println("One month earlier:", oneMonthEarlier)
}

8. 获取和设置时区

Go 中的 time.Time 类型支持时区。可以通过 time.Localtime.UTC 等来获取时间的时区,也可以设置特定的时区。

获取和设置时区

go
package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()

	// 获取当前时区
	fmt.Println("Current time zone:", now.Location())

	// 设置时区为 UTC
	utcTime := now.UTC()
	fmt.Println("Current time in UTC:", utcTime)

	// 设置时区为一个特定的时区
	location, _ := time.LoadLocation("Asia/Shanghai")
	ShanghaiTime := now.In(location)
	fmt.Println("Current time in Shanghai:", ShanghaiTime)
}

9. 定时事件的模拟

你可以使用 time.After 来创建一个定时事件,它会在指定的时间间隔后触发。

go
package main

import (
	"fmt"
	"time"
)

func main() {
	// 3秒后触发
	select {
	case <-time.After(3 * time.Second):
		fmt.Println("3 seconds passed")
	}
}

总结

  • 获取当前时间time.Now()
  • 时间格式化time.Format()
  • 时间解析time.Parse()
  • Unix 时间戳time.Unix(), time.Now().Unix()
  • 时间间隔time.Duration,例如 time.Hour, time.Minute
  • 定时器time.NewTimer(), time.NewTicker()
  • 比较时间time.TimeBefore(), After(), Equal()
  • 时区time.Local, time.UTC, time.LoadLocation()

Go 中的 time 包功能强大,支持对时间和日期进行各种操作,可以广泛应用于定时任务、时间计算、时区转换等场景。