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 ", 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 ", year, month, day, hour, minute)
11: time_stamp := now.Unix()12: fmt.Printf("time_stamp_year:%d ", time_stamp/3600/24/30/12)
13: }
另外一种格式化输出(Go语言诞生时间,具体时间是固定的):
1: fmt.Printf(now.Format("02/1/2006 15:04 "))
2: fmt.Printf(now.Format("2006/1/02 15:04 "))
3: fmt.Printf(now.Format("2006/1/02 "))
输出:
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 ", 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 ")
3: }4: func testTicker(){5: ticker := time.Tick(2*time.Second)6: for i := range ticker {7: fmt.Printf("%v ", 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 ", 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 ", 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: }