🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
os和time 时间和日期类型 1、time包 2、time.Time类型,用来 表示时间 3、获取当前时间,now:=time.Now() func nowtime() { var now time.Time now = time.Now() fmt.Printf("now is :%v\n",now) } 4、time.Now().Day() time.Now().Minute() time.Now().Month() time.Now().Year() 5、格式化输出 func nowtime() { var now time.Time now = time.Now() fmt.Printf("now is :%v\n",now) fmt.Printf("year is :%v,month is :%v,day is :%v,minute is :%v", now.Year(),now.Month(),now.Day(),now.Minute()) } 6、获取当前的时间戳 time.Now().Unix() fmt.Printf("timestamp is :%d ns:%d\n",now.Unix(),now.UnixNano()) 7、时间戳转换成time func timeStampToTime(timestamp int64) { t := time.Unix(timestamp,0) fmt.Printf("time :%v\n",t) } func main(){ now := time.Now() timeStampToTime(now.Unix()) } 8、定时器的简单使用 func testtimer() { //NewTimer定时器,只触发一次 ticker := time.NewTimer(time.Second) for v := range ticker.C { fmt.Printf("time:%v\n",v) //reset会将ticker时间重置,否则会将队列堵塞 ticker.Reset(time.Second) } } 9、time.Duration 用来表示纳秒 10、一些常量 const( NanosecondDuration = 1 //纳秒 Microsecond = 1000 * NanosecondDuration //微秒 Millisecond = 1000 * Microsecond //毫秒 second = 1000 * Millisecond //秒 Minute = 60 * second //分钟 Hour = 60 * Minute //小时 ) 11、格式化 func priTest() { now := time.Now() fmt.Println(now.Format("02/1/2006 15:04")) fmt.Println(now.Format("2006/1/02/ 15:04:05")) } "2006/1/02/ 15:04" 传入的时间参数必须是这个数,这个数是go的诞生时间,否则打印出的时间是一个乱码 练习:统计一段代码的执行耗时,单位精确到微秒 package main import( "fmt" "time" ) func test() { for i:= 0; i<100000000;i++ { _ = i } } func main() { start := time.Now().UnixNano() test() stop := time.Now().UnixNano() fmt.Printf("cost is %d\n", (stop - start)/1000/1000) } 1、练习:获取当前的主机名和环境变量PATH的值 ~~~ package main import ( "os" "fmt" ) func main() { name,err := os.Hostname() fmt.Printf("%s %v\n",name ,err) val := os.Getenv("PATH") fmt.Printf("%s\n",val) } ~~~ 2、练习:将两个变量值互换。打印出随机的10个小于100的整数,10个随机的浮点数 ~~~ package main import ( "fmt" "math/rand" ) func Change(a int,b int) (int,int) { var c int c = a a = b b = c return a ,b } func Rd() { for i := 0;i < 10;i++ { fmt.Println(rand.Intn(100)) fmt.Println(rand.Float64()) fmt.Println((rand.Float64()*5)+5) } } func main() { a,b := Change(1,2) fmt.Printf("a=%v,b=%v\n",a,b) Rd() } ~~~