package main import ( "fmt"
"time" ) func main(){ //【時間獲取及格式化】 //獲取當前時間
now_time := time.Now() fmt.Printf("Now_time=%v,數據類型:%T", now_time, now_time) //通過now獲取年月日時分秒
fmt.Printf("年=%v\n", now_time.Year()) fmt.Printf("月=%v\n", now_time.Month()) //默認是英文的月份
fmt.Printf("月=%v\n", int(now_time.Month())) //加int轉換為數字
fmt.Printf("日=%v\n", now_time.Day()) fmt.Printf("時=%v\n", now_time.Hour()) fmt.Printf("分=%v\n", now_time.Minute()) fmt.Printf("秒=%v\n", now_time.Second()) //格式化日期時間①
fmt.Printf("當前時間 %d-%d-%d %d:%d:%d \n", now_time.Year(), int(now_time.Month()), now_time.Day(), now_time.Hour(), now_time.Minute(), now_time.Second()) //把格式化好的時間返回給一個變量,然后輸出
date_now := fmt.Sprintf("當前時間 %d-%d-%d %d:%d:%d \n", now_time.Year(), int(now_time.Month()), now_time.Day(), now_time.Hour(), now_time.Minute(), now_time.Second()) fmt.Printf("date:%v\n", date_now) //格式化日期時間② //2006/01/02 15:04:05 這里必須數字一個不差的寫 //據說是因為golang設計者在這個時間有設計golang的想法
fmt.Printf(now_time.Format("2006/01/02 15:04:05\n")) fmt.Printf(now_time.Format("2006/01/02\n")) fmt.Printf(now_time.Format("15:04:05\n")) //【時間常量應用】 //時間單位換算 // const { // Nanosecond Duration = 1 //納秒 // Microsecond = 1000 * Nanosecond //微秒 // Millisecond = 1000 * Microsecond //毫秒 // Second = 1000 * Millisecond //秒 // Minute = 60 * Second //分鍾 // Hour = 60 * Minute //小時 // } //每隔1秒輸出一個數字,到100停止
i := 0
for { i++ fmt.Println(i) //休眠
time.Sleep(time.Second) if i == 100 { break } } //每隔0.1秒輸出一個數字,到100停止
i := 0
for { i++ fmt.Println(i) //休眠 //這里不能用time.Second *0.1,會有異常
time.Sleep(time.Millisecond * 100) if i == 100 { break } } //獲取當前時間戳還有納秒時間戳,相當於php中的time和microtime
fmt.Printf("unix時間戳=%v,unix納秒時間戳=%v", now_time.Unix(), now_time.UnixNano()) }
測試函數執行時間
package main import ( "fmt"
"time"
"strconv" ) //測試函數
func test_func() { str := "" //聲明一個字符串
for i := 0; i < 100000; i++ { //for循環10W次拼接
str += "golang" + strconv.Itoa(i) //整數轉字符串拼接
} } func main(){ //測試test_func的執行時間
start := time.Now().Unix() test_func() end := time.Now().Unix() fmt.Printf("執行消耗的時間為:%v秒", end - start) }
D:\goproject\src\main>go run hello.go 執行消耗的時間為:10秒