Golang学习笔记(09-4-time包)

142 阅读3分钟

1. 常用函数和方法

1.  time.Now()
    Func:   func Now() Time  // 取变量 now := time.Now()
    Man:    Now返回当前本地时间,注意为 Time struct 类型
    
2.  取 time.Now() 中具体时间信息
    Func:   func (t Time) Year() int                        // 年
            func (t Time) Month() Month                     // 月,可强转为int
            func (t Time) Day() int                         // 日
            func (t Time) Hour() int                        // 时(0-23)
            func (t Time) Minute() int                      // 分
            func (t Time) Second() int                      // 秒
            func (t Time) Nanosecond() int                  // 纳秒
            func (t Time) YearDay() int                     // 一年中的第多少天
            func (t Time) Zone() (name string, offset int)  // 时区和相对于UTC的偏移量(秒)
            
3.  取时间戳
    Func:   func (t Time) Unix() int64      // 从1970-01-01 00:00:00 UTC 到现在的秒数
            func (t Time) UnixNano() int64  // 从1970-01-01 00:00:00 UTC 到现在的纳秒数
    
4.  时间比较
    Func:   func (t Time) After(u Time) bool    // t 在 u 之后为真
            func (t Time) Before(u Time) bool   // t 在 u 之前为真
            func (t Time) Equal(u Time) bool    // t 与 u 相等为真

5.  时间运算
    Func:   func (t Time) AddDate(years int, months int, days int) Time  // 加上指定时间,参数支持负数
            func (t Time) Sub(u Time) Duration  // 时间相减

6.  格式化时间为字符串
    Func:   func (t Time) Format(layout string) string  // layout必须为"2006-01-02 15:04:05"的时刻
            
7.  其它格式转时间格式
    Func:   func Parse(layout, value string) (Time, error)  // 将字符串格式转为为 Time
            func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time // 转为Time,loc为时区
            func Unix(sec int64, nsec int64) Time           // 将秒和纳秒转为Time
       
8.  time.Sleep()
    Func:   func Sleep(d Duration)
    Man:    Sleep阻塞当前go进程至少d代表的时间段。d<=0时,Sleep会立刻返回

9.  定时器
		type Ticker struct {
      C <-chan Time // 周期性传递时间信息的通道,容量为1
      // 内含隐藏或非导出字段
		}
		
10. NewTicker()
		Func:  func NewTicker(d Duration) *Ticker
    Man:   返回定时器,每隔 d 时间就会向定时器中发送一个时间戳.使用完毕后需要手动关闭

11. 关闭计时器
		Func:  func (t *Ticker) Stop()
    Man:   关闭不必要的定时器
    
12. Tick()
		Func:  func Tick(d Duration) <-chan Time
    Man:   返回一个 Ticker.C 的通道,一般在不需要关闭定时器的任务中使用,比如项目中的计划任务

12. 常量
    Nanosecond  Duration = 1
    Microsecond          = 1000 * Nanosecond
    Millisecond          = 1000 * Microsecond
    Second               = 1000 * Millisecond
    Minute               = 60 * Second
    Hour                 = 60 * Minute

2. 案例

2.1. 取当前时间信息

package main

import (
	"fmt"
	"strings"
	"time"
)

func main()  {
	// 取当前时间
	fmt.Println("当前本地时间:", time.Now())      // 当前本地时间
	fmt.Println("当前UTC时间:", time.Now().UTC()) // 当前UTC时间
	fmt.Println(strings.Repeat("--", 20))

	// 格式化时间, 将time转为格式化好的字符串
	now := time.Now()
	timeStr := fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d", now.Year(), now.Month(),now.Day(),
		now.Hour(),now.Minute(),now.Second())
	timeRes := now.Format("2006-01-02 15:04:05")
	fmt.Printf("timeStr: type=%T  value=%q\n", timeStr, timeStr)
	fmt.Printf("timeRes: type=%T  value=%q\n", timeRes, timeRes)
	fmt.Println(strings.Repeat("--", 20))

	// 获取时间戳
	fmt.Printf("秒数时间戳:%d; 纳秒时间戳:%d\n", now.Unix(), now.UnixNano())
}
[root@heyingsheng src]# go run studygo/day03/15-time/main.go
当前本地时间: 2020-03-22 22:06:57.2284622 +0800 CST m=+0.001994401
当前UTC时间: 2020-03-22 14:06:57.2494063 +0000 UTC
----------------------------------------
timeStr: type=string  value="2020-03-22 22:06:57"
timeRes: type=string  value="2020-03-22 22:06:57"
----------------------------------------
秒数时间戳:1584886017; 纳秒时间戳:1584886017250438600

2.2. 休眠函数

package main

import (
	"fmt"
	"time"
)

func main()  {
	for i:=0;i<10;i++ {
		fmt.Printf("%s --> %d \n", time.Now().Format("15:04:05"), i)
		time.Sleep(time.Millisecond * 500)
	}
}
[root@heyingsheng src]# go run studygo/day03/15-time/sleep.go
22:11:34 --> 0
22:11:34 --> 1
22:11:35 --> 2
22:11:35 --> 3
22:11:36 --> 4
22:11:36 --> 5
22:11:37 --> 6
22:11:37 --> 7
22:11:38 --> 8
22:11:38 --> 9

2.3. 统计代码时间

package main

import (
	"fmt"
	"time"
)

func f0(n int) int {
	ret := 1
	if n > 2 {
		ret = f0(n-1) + f0(n-2)
	}
	return ret
}

func f1(n int) int {
	x, y := 1, 1
	for i:=3; i<=n; i++ {
		x += y
		y = x - y
	}
	return x
}

func main()  {
	start := time.Now().UnixNano()
	ret0 := f0(45)
	stop1 := time.Now().UnixNano()
	ret1 := f1(45)
	stop2 := time.Now().UnixNano()
	fmt.Printf("f0(50): time=%dms value=%d\n", (stop1-start)/1000/1000, ret0)
	fmt.Printf("f1(50): time=%dms value=%d\n", (stop2-stop1)/1000/1000, ret1)
}
[root@heyingsheng src]# go run studygo/day03/15-time/const.go
f0(50): time=4125ms value=1134903170
f1(50): time=0ms value=1134903170

2.4. 定时器

定时器的应用非常广泛,在代码中的计划任务就常用这种方式实现,或者在任务超时退出的场合也会使用。

package main

import (
	"fmt"
	"time"
)

func main() {
	go func() {
		tick := time.Tick(time.Second * 5)
		for v := range tick {
			fmt.Printf("定时任务, time:%s\n", v)
		}
	}()
	select {}
}
[root@heyingsheng day26]# go run main.go
定时任务, time:2020-09-03 22:25:19.0521376 +0800 CST m=+5.000276201
定时任务, time:2020-09-03 22:25:24.052156 +0800 CST m=+10.000294501
定时任务, time:2020-09-03 22:25:29.0524934 +0800 CST m=+15.000632101
定时任务, time:2020-09-03 22:25:34.0524382 +0800 CST m=+20.000576801