[TOC] ## time.Ticker 间隔执行功能 每3秒输出 hello word ``` type hello struct { say string ticker *time.Ticker } func NewHello(interval time.Duration, say string) *hello { return &hello{ say: say, ticker: time.NewTicker(interval * time.Second), } } func (h *hello) start() { for { select { case <-h.ticker.C: fmt.Println(h.say) } } } func main() { // 每个3秒输出一个 hello word h := NewHello(3, "hello word") h.start() } ``` ## time.After 延迟执行 ``` a := time.Tick(1 * time.Second) //每秒触发一次 b := time.After(5 * time.Second) //五秒触发一次, 只触发一次 for { select { case <-a: fmt.Println("每秒触发一次") case <-b: fmt.Println("五秒后触发") } } ``` ## 格式化和解析 ### Parse / ParseInLocation 格式化转time ParseInLocation 转当地时间 方法一 ``` t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2016-06-13 09:14:00", time.Local) fmt.Println(t.Unix()) ``` 方法二: ``` location, e := time.LoadLocation("Asia/Shanghai") if e != nil { fmt.Println(e) } t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2016-06-13 09:14:00", location) ``` Parse 转为0时区的时间 ``` t, _ := time.Parse("2006-01-02 15:04:05", "2016-06-13 09:14:00") fmt.Println(t.Unix()) ``` ### Now.Format 格式化时间戳->转格式化 `time.Now().Format("2006-01-02 15:04:05") //2019-05-09 15:13:38` ## 时间差值 ``` start := time.Now() time.Sleep(1 * time.Second) fmt.Println(time.Now().Sub(start)) //1.0006197s ``` ## 时间取整 ``` t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2016-06-13 15:34:39", time.Local) // 整点(向下取整) fmt.Println(t.Truncate(1 * time.Hour)) //2016-06-13 15:00:00 +0800 CST // 整点(最接近) fmt.Println(t.Round(1 * time.Hour)) ```