GO–时间和日期函数
介绍:
- 在编程中,经常使用到的日期相关的函数
- 时间和日期相关函数,需要导入 time 包
包:
-
time.Time类型,用于获取当前时间
-
package main import ( "fmt" "time" ) func main() { // 获取当前时间 now := time.Now() fmt.Printf("now=%v ", now) //now=2020-07-06 18:16:07.518698 +0800 CST m=+0.000069675 }
-
-
用于获取详细的年月日时分秒
-
package main import ( "fmt" "time" ) func main() { // 获取当前时间 now := time.Now() fmt.Printf("now=%v ", now) //now=2020-07-06 18:16:07.518698 +0800 CST m=+0.000069675 // 通过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("当前年月日 %d-%d-%d %d:%d:%d \n", now.Year(),now.Month(), now.Day(), now.Hour(), now.Minute(), now.Year())//当前年月日 2020-7-6 21:10:2020 dateStr := fmt.Sprintf("当前年月日 %d-%d-%d %d:%d:%d\n", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second()) fmt.Printf("dateStr=%v\n", dateStr)//dateStr=当前年月日 2020-7-6 21:10:27
-
方式二:使用 time.Format()方法完成
fmt.Printf(now.Format("2006-01-02 15:04:05")) fmt.Println()//2020-07-06 21:14:34 fmt.Printf(now.Format("2006-01-02")) fmt.Println()//2020-07-06 fmt.Printf(now.Format("15:04:05")) fmt.Println()//21:14:34
-
-
时间和日期的相关函数
-
时间的常量
-
常量的作用:在程序中可用于获取指定时间单位的时间,比如想得到100毫秒
-
100 * time.Millisecond
-
const { Hour = 60 * Minute//小时 Minut = 60 * Second//分钟 Second = 1000 * Millisecond//秒 Millisecond = 1000 * Microsecond //毫秒 }
-
休眠:func Sleep(d Duration) 结合Sleep来使用一下时间常量
-
package main import ( "fmt" "time" ) func main() { // 需求:每隔 0.1 秒中打印一个数字,打印到100时就退出 i := 0 for { i++ fmt.Println(i) time.Sleep(time.Millisecond * 100) if i == 100 { break } } }
-
-
-
获取当前unix时间戳 和 unixnano 时间戳(作用是可以获取随机数)
- Unix:返回1970年至今的秒数
- Unixnano:返回1970年至今的纳秒数
-
-
实例:编写一段代码来统计,函数test03执行的时间
-
package main import ( "fmt" "strconv" "time" ) func test01() { str := "" for i := 0; i < 100000; i++ { str += "hello" + strconv.Itoa(i) } } func main() { start := time.Now().Unix() test01() end := time.Now().Unix() fmt.Printf("执行test01()耗费时间为%v秒\n", end-start)//执行test01()耗费时间为7秒 }
-