go语言标准库 - time

1,205 阅读2分钟

一、目录

二、简介

该包提供了对于时间的显示、转换以及控制。
精度一直实现到纳秒

1. 显示

type Duration int64 显示时间间隔
type Location struct 设置显示的时区
type Month int 显示月份
type Weekday int 显示星期
type ParseError struct 解析错误

2. 转换

type Time struct 时间转换

3. 控制

type Ticker struct 时钟
type Timer struct

三、实例

1. 等待固定时间间隔,返回Time结构体

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println("begin")
	resTime := <-time.After(3 * time.Second)
	fmt.Printf(
		"after 3 second\nNow the time is %s\n",
		resTime.Format("2006-01-02 15:04:05"))
}

2. 暂停当前协程

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println("begin")
	time.Sleep(3000 * time.Millisecond)
	fmt.Printf("after 3 second\n")
}

3. 定时器

package main

import (
	"fmt"
	"log"
	"time"
)

func main() {
	locate, _ := time.LoadLocation("Asia/Shanghai")
	c := time.Tick(2 * time.Second)
	i := 0
	for now := range c {
		i++
		fmt.Printf(
			"%s, 定时器第%d次运行\n",
			now.In(locate).Format("2006-01-02 15:04:05"), i)

	}
}

4. 时间间隔

时间间隔(type Duration int64)以纳秒为最小单元

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

因为Duration也为int类型,所以上面的代码可以通过 2 * time.Second 的方式获得对应的数字。
这个数字可以作为Duration传入函数中。

5. 选择时区

package main

import (
	"fmt"
	"log"
	"time"
)

func main() {
	locate, _ := time.LoadLocation("Asia/Shanghai")
	fmt.Printf(
		"当前时区:%s, 当前时间:%s\n", locate.String(),
		time.Now().In(locate).Format("2006-01-02 15:04:05"))

	locate2 := time.FixedZone("UTC-8", 0)
	fmt.Printf("当前时区:%s(东八区),当前时间:%s\n",
		locate2.String(),
		time.Now().In(locate2).Format("2006-01-02 15:04:05"))
}

6. 计时器

package main

import (
	"fmt"
	"log"
	"time"
)

func main() {
	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()
	for {
		t := <-ticker.C
		fmt.Println(t.In(time.FixedZone("UTC-8", 0)).Format("2006-01-02 15:04:05"))
	}
}

7. 时间戳和日期相互转换

package main

import (
	"fmt"
	"log"
	"time"
)

func main() {
	// 时间戳转日期时间
	curDateTime := time.Now().In(time.FixedZone("UTC-8", 0)).Format("2006-01-02 15:04:05")
	fmt.Println(curDateTime)
	// 日期转时间戳
	parseTime, _ := time.Parse("2006-01-02 15:04:05", curDateTime)
	fmt.Println(parseTime.Unix())
}