golang中的时间

发布时间:2018-04-06 22:25:36
Go 

正文

生成定时器

package main

import (
	"time"
	"fmt"
)

func main() {
	//生成一个定时器
	c := time.Tick(time.Second)
	for now := range c {
		fmt.Printf("%v\n", now)
	}
}

执行结果

2018-04-06 22:02:07.728955 +0800 CST m=+1.002279501
2018-04-06 22:02:08.731189 +0800 CST m=+2.004503872
2018-04-06 22:02:09.729996 +0800 CST m=+3.003299715
2018-04-06 22:02:10.7278 +0800 CST m=+4.001092850

计算耗时时间

package main

import (
	"time"
	"fmt"
)

func main() {
	t0 := time.Now()
	work()
	t1 := time.Now()
	fmt.Printf("spend time: %v", t1.Sub(t0))
}

func work() {
	for i := 0; i < 1000000; i++ {
	}
}

执行结果

spend time: 555.211µs

解析文本时间

支持的单位:Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

package main

import (
	"time"
	"fmt"
)

func main() {
	t1, _ := time.ParseDuration("1h")
	fmt.Printf("t1: %v\n", t1.Seconds())
	t2, _ := time.ParseDuration("-1h")
	fmt.Printf("t2: %v\n", t2.Seconds())
}

执行结果

t1: 3600
t2: -3600

UTC时间

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println(time.Now().UTC())
	fmt.Println(time.Now())
}

运行结果

2018-04-07 10:25:00.141315 +0000 UTC
2018-04-07 18:25:00.141377 +0800 CST m=+0.000386440

参考

原文地址:http://zhyoulun.com/post/time-in-golang
转载请注明出处