说明
在编程中,会经常使用到日期相关的函数,比如:统计某段代码执行花费的时间等等
基本用法
- 1.time.Time类型,用于表示时间
- 2.获取到当前时间的方法:now := time.Now // now的类型就是time.Time
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Printf("now=%v now type=%T", now, now)
}
//now=2023-01-08 21:46:04.0178332 +0800 CST m=+0.002207501 now type=time.Time
3.获取到其他日期的信息
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
//通过now可以获取到年月日时分秒
fmt.Printf("年=%v\n", now.Year())
fmt.Printf("月=%v\n", now.Month())
fmt.Printf("月=%v\n", int(now.Month()))
fmt.Printf("日=%v\n", now.Day())
fmt.Printf("时=%v\n", now.Hour())
fmt.Printf("分=%v\n", now.Minute())
fmt.Printf("秒=%v\n", now.Second())
//格式化时间
fmt.Printf("当前年月日 %02d-%02d-%02d %02d-%02d-%02d \n",
now.Year(), now.Month(), now.Day(),
now.Hour(), now.Minute(), now.Second())
//格式化时间的第二种方式
//"2006-01-02 15:04:05"这个字符串的各个数字是固定的,必须这样写
//"2006-01-02 15:04:05"这个字符串各个数字可以自由的组合,可以按照程序需求返回时间和日期
fmt.Printf("now.Format(2006-01-02 15:04:05)")
fmt.Println()
fmt.Printf("now.Format(2006-01-02 )")
fmt.Println()
fmt.Printf("now.Format(15:04:05)")
fmt.Println()
}
/*
年=2023
月=January
月=1
日=8
时=22
分=16
秒=55
当前年月日 2023-01-08 22-16-55
now.Format(2006-01-02 15:04:05)
now.Format(2006-01-02 )
now.Format(15:04:05)
*/
- 4.时间的常量,作用:在程序中可用于获取指定时间单位的时间,比如得到100毫秒
i := 0
for {
i++
fmt.Println(i)
//休眠
time.Sleep(time.Second)
if i == 20 {
break
}
}
- 5.获取当前Unix时间戳和unixnano时间戳(作用是可以获取随机数字)
fmt.Printf("unix时间戳=%v unixnano=%v", now.Unix(), now.UnixNano())
//unix时间戳=1673188257 unixnano=1673188257498223400
案例
获取一段代码的执行时间
package main
import (
"fmt"
"time"
"strconv"
)
func test() {
str := ""
for i := 0; i < 100000; i++ {
str += "hello" + strconv.Itoa(i)
}
}
func main() {
//在执行test前,先获取当前的unix时间戳
start := time.Now().Unix()
test()
end := time.Now().Unix()
fmt.Printf("执行test()耗费时间为%v秒\n", end-start)
}
/*
执行test()耗费时间为12秒
*/