Go語言學習筆記(五)
阿新 • • 發佈:2018-12-08
11.時間和日期型別(time包)
a.time.Time用來表示時間,time.Now()獲取當前時間
b.time.Now().Day(),time.Now().Minute(), time.Now().Month(),time.Now().Year(),
類似的還有Hour,Minute,Second
c.格式化輸出fmt.Printf("%02d/%02d%02d%02d:%02d:%02d", now.Year()……)
1: func testTime(){2: now := time.Now()
3: fmt.Printf("now_time:%v\n", now)
4:5: year := now.Year()6: month := now.Month()7: day := now.Day()8: hour := now.Hour()9: minute := now.Minute()10: fmt.Printf("%02d-%02d-%02d-%02d-%02d\n", year, month, day, hour, minute)
11: time_stamp := now.Unix()12: fmt.Printf("time_stamp_year:%d\n", time_stamp/3600/24/30/12)
13: }
另外一種格式化輸出(Go語言誕生時間,具體時間是固定的):
1: fmt.Printf(now.Format("02/1/2006 15:04\n"))
2: fmt.Printf(now.Format("2006/1/02 15:04\n"))
3: fmt.Printf(now.Format("2006/1/02\n"))
輸出:
1: 08/12/2018 16:102: 2018/12/08 16:103: 2018/12/08
d.獲取當前的時間戳:time.Now().Unix(),時間戳可以轉Time型別
1: func testTimestamp(timestamp int64) {2: timeObj := time.Unix(timestamp, 0)
3: year := timeObj.Year()4: month := timeObj.Month()5: day := timeObj.Day()6: hour := timeObj.Hour()7: minute := timeObj.Minute()8: fmt.Printf("%02d-%02d-%02d-%02d-%02d\n", year, month, day, hour, minute)
9: }10: func main(){11: // testTime()
12: time_stamp := time.Now().Unix()
13: testTimestamp(time_stamp)14: }
e.定時器的簡單用法
1: func processTask(){2: fmt.Printf("do task\n")
3: }4: func testTicker(){5: ticker := time.Tick(2*time.Second)6: for i := range ticker {7: fmt.Printf("%v\n", i)
8: processTask()9: }10: }
f.time.Duration表示納秒
一些常量:
1: const(2: Nanosecond Duration = 13: Microsecond = 1000*Nanosecond4: Millisecond = 1000*Microsecond5: Second = 1000*Millisecond6: Minute = 60*Second7: Hour = 60*Minute8: )
小練習:
1.獲取當前時間,並格式化成2017/06/15 08:05:00
兩種寫法
1: func get_time(){2: now := time.Now()
3: year := now.Year()4: month := now.Month()5: day := now.Day()6: hour := now.Hour()7: minute := now.Minute()8: second := now.Second()9: fmt.Printf("%04d/%02d/%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
10: }11:12: func get_time_2(){13: now := time.Now()
14: timeStr := now.Format("2006/01/02 15:04:05")
15: fmt.Printf("time:%v\n", timeStr)
16: }
2.統計一段程式碼的執行耗時,單位精確到微秒
1: func testCost(){2: start := time.Now().UnixNano()3: for i:=0;i<10;i++{4: time.Sleep(time.Millisecond)5: }6: end := time.Now().UnixNano()7: cost := (end - start)/10008: fmt.Printf("cost:%d", cost)
9: }