时间转换

字符串转时间

time.Parse()

时间转字符串

time.Format()

时间转时间戳

Time.Unix()

时间戳转时间

time.Unix()
计时

朴素方法

	startTime := time.Now()
	//do something
	time.Sleep(time.Second)
	duration := time.Since(startTime)
	fmt.Printf("经过时间:%v\n", duration)
	
//经过时间:1.005046959s

简洁方法

// TimeCost 耗时统计函数
func TimeCost(start time.Time) {
	duration := time.Since(start)
	fmt.Printf("经过时间:%v\n", duration)
}

	defer TimeCost(time.Now())
	//do something
	time.Sleep(time.Second)
	
//经过时间:1.005054375s

优雅方法

// TimeCost 耗时统计函数
func TimeCost() func() {
	start := time.Now()
	return func() {
		duration := time.Since(start)
		fmt.Printf("经过时间:%v\n", duration)
	}
}

	defer TimeCost()()
	//do something
	time.Sleep(time.Second)
	
//经过时间:1.005033916s
时间的加减法
	// Add 时间相加
	now := time.Now()
	// ParseDuration parses a duration string.
	// A duration string is a possibly signed sequence of decimal numbers,
	// each with optional fraction and a unit suffix,
	// such as "300ms", "-1.5h" or "2h45m".
	//  Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
	// 10分钟前
	m, _ := time.ParseDuration("-1m")
	m1 := now.Add(m)
	fmt.Println(m1)

	// 8个小时前
	h, _ := time.ParseDuration("-1h")
	h1 := now.Add(8 * h)
	fmt.Println(h1)

	// 一天前
	d, _ := time.ParseDuration("-24h")
	d1 := now.Add(d)
	fmt.Println(d1)

	// 10分钟后
	mm, _ := time.ParseDuration("1m")
	mm1 := now.Add(mm)
	fmt.Println(mm1)

	// 8小时后
	hh, _ := time.ParseDuration("1h")
	hh1 := now.Add(hh)
	fmt.Println(hh1)

	// 一天后
	dd, _ := time.ParseDuration("24h")
	dd1 := now.Add(dd)
	fmt.Println(dd1)

	// Sub 计算两个时间差
	subM := now.Sub(m1)
	fmt.Println(subM.Minutes(), "分钟")

	sumH := now.Sub(h1)
	fmt.Println(sumH.Hours(), "小时")

	sumD := now.Sub(d1)
	fmt.Printf("%v 天\n", sumD.Hours()/24)
go get 下载指定版本
go get github.com/ormissia/go-opv@v0.0.2
go chan close

gochan中,chan被关闭后,消费者会继续读取channel中的消息。直到消息被全部读取之后使用i, ok := <-ch得到的ok才会变为false

下面是测试代码以及运行时控制台打印结果:

func main() {
	ch := make(chan int, 3)

	go producer(ch)

	for {
		i, ok := <-ch
		fmt.Printf("consume msg: %d\tok: %v\n", i, ok)
		time.Sleep(time.Second * 3)
	}

}

func producer(ch chan int) {
	for i := 0; i < 10; i++ {
		ch <- i
		fmt.Printf("produce msg: %d\n", i)
		time.Sleep(time.Second)
	}
	close(ch)
	fmt.Println("chan closed")
}

输出结果

produce msg: 0
consume msg: 0	ok: true
produce msg: 1
produce msg: 2
consume msg: 1	ok: true
produce msg: 3
produce msg: 4
consume msg: 2	ok: true
produce msg: 5
consume msg: 3	ok: true
produce msg: 6
consume msg: 4	ok: true
produce msg: 7
consume msg: 5	ok: true
produce msg: 8
consume msg: 6	ok: true
produce msg: 9
chan closed
consume msg: 7	ok: true
consume msg: 8	ok: true
consume msg: 9	ok: true
consume msg: 0	ok: false
consume msg: 0	ok: false