Go筆記-時間

當前時間

可使用 time.Now() 獲取,或者使用 t.Day()t.Minute() 等等來獲取時間的一部分;你甚至能夠自定義時間格式化字符串,例如: fmt.Printf("%02d.%02d.%4d\n」, t.Day(), t.Month(), t.Year()) 將會輸出 21.07.2011。ide

time.Nanosecond() 並非從70年開始的納秒,UnixNano() 纔是。函數

函數執行時間

start := time.Now()
doSomeThing()
end := time.Now()
delta := end.Sub(start)
fmt.Printf("doSomeThing took this amount of time: %s\n", delta) // 納秒

格式化時間

func Now() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

輸出示例:ui

2015-03-15 09:48:34
y, m, d := time.Now().Date()
	h, mi, s := time.Now().Clock()
	fmt.Printf("如今是:%d年%d月%d日 %d時%d分%d秒 \n", y, m, d, h, mi, s)

輸出:this

如今是:2015年3月15日 9時55分12秒

timezone

now := time.Now()
	s := now.Format("20060102150405")
	t, err := time.Parse("20060102150405", s)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(now, t)

上面輸出:2016-01-25 19:15:31.21773073 +0800 CST 2016-01-25 19:15:31 +0000 UTCcode

Parse是按照UTC來解析的。orm

若是想按照本地時區來解析的話使用:time.ParseInLocation("20060102150405", s, time.Local)資源

定時器

time.NewTimer(time.Second * 2)

NewTimer建立一個Timer,它會在最少過去時間段d後到期,向其自身的C字段發送當時的時間。字符串

// Timers represent a single event in the future. You
	// tell the timer how long you want to wait, and it
	// provides a channel that will be notified at that
	// time. This timer will wait 2 seconds.
	timer1 := time.NewTimer(time.Second * 2)

	// The `<-timer1.C` blocks on the timer's channel `C`
	// until it sends a value indicating that the timer
	// expired.
	<-timer1.C
	fmt.Println("Timer 1 expired")

	// If you just wanted to wait, you could have used
	// `time.Sleep`. One reason a timer may be useful is
	// that you can cancel the timer before it expires.
	// Here's an example of that.
	timer2 := time.NewTimer(time.Second)
	go func() {
		<-timer2.C
		fmt.Println("Timer 2 expired")
	}()
	stop2 := timer2.Stop()
	if stop2 {
		fmt.Println("Timer 2 stopped")
	}

運行結果string

Timer 1 expired
Timer 2 stopped

Ticker

time.NewTicker(time.Millisecond * 500)

NewTicker返回一個新的Ticker,該Ticker包含一個通道字段,並會每隔時間段d就向該通道發送當時的時間。它會調整時間間隔或者丟棄tick信息以適應反應慢的接收者。若是d<=0會panic。關閉該Ticker能夠釋放相關資源。it

// Tickers use a similar mechanism to timers: a
	// channel that is sent values. Here we'll use the
	// `range` builtin on the channel to iterate over
	// the values as they arrive every 500ms.
	ticker := time.NewTicker(time.Millisecond * 500)
	go func() {
		for t := range ticker.C {
			fmt.Println("Tick at", t)
		}
	}()

	// Tickers can be stopped like timers. Once a ticker
	// is stopped it won't receive any more values on its
	// channel. We'll stop ours after 1500ms.
	time.Sleep(time.Millisecond * 1500)
	ticker.Stop()
	fmt.Println("Ticker stopped")

運行結果

Tick at 2015-04-22 09:58:52.048046619 +0800 CST
Tick at 2015-04-22 09:58:52.548034081 +0800 CST
Tick at 2015-04-22 09:58:53.048019367 +0800 CST
Ticker stopped
相關文章
相關標籤/搜索