Golang——时间日期函数
生活随笔
收集整理的這篇文章主要介紹了
Golang——时间日期函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
時間:
func main() {// 獲取當前時間now := time.Now()fmt.Println("當前時間:", now)// 獲取年月日時分秒fmt.Println("年:", now.Year())fmt.Println("月:", int(now.Month())) // 不轉int是英文的月份fmt.Println("日:", now.Day())fmt.Println("時:", now.Hour())fmt.Println("分:", now.Minute())fmt.Println("秒:", now.Second())fmt.Println("1000毫秒:", time.Millisecond*1000)fmt.Println("星期幾:", int(now.Weekday())) // 不轉int是英文的星期數fmt.Println("一年中的第幾天:", now.YearDay())fmt.Println("時區:", now.Location())// 返回一年中第幾天fmt.Println(now.YearDay())// 可以使用Sleeptime.Sleep(time.Millisecond * 2000)// 時間戳,時間戳是1970/1/1日到現在的時間fmt.Println("秒時間戳,返回整數:", now.Unix())fmt.Println("時間戳小數的部分:", now.Nanosecond())fmt.Println("納秒時間戳,返回整數:", now.UnixNano()) }日期:
func main() {now := time.Now()// 格式化日期時間fmt.Printf("當前時間: %d-%d-%d %d:%d:%d", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())// 也可以賦值給變量,再處理date := fmt.Sprintf("當前時間: %d-%d-%d %d:%d:%d", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())fmt.Println(date)// 使用Format格式化fmt.Println("年月日時分秒:", now.Format("2006/01/02 15:04:05")) // 當前時間fmt.Println("年月日時分:", now.Format("2006/01/02 15:04"))fmt.Println("年月日時:", now.Format("2006/01/02 15"))fmt.Println("年月日:", now.Format("2006-01-02"))fmt.Println("時分秒", now.Format("15:03:04"))// 時間只能是"2006/01/02 15:04:05",不可以是"YYYY/mm/dd"這種類型的fmt.Println("當前時間:", now.Format("YYYY/mm/dd")) }時間戳格式轉換:
func main() {now := time.Now()nowDate := "2006-01-02 15:04:05"t := time.Unix(now.Unix(), 0) // sec:秒 nsec:納秒fmt.Println(t.Format(nowDate)) }計算函數執行時間:
func dateTest() {startTime := time.Now()sum := 0for i := 0; i < 10000000000; i++ {sum++}// Sub方法讓兩個時間點相減,生成一個Duration類型值(代表時間段)elapsedTime := time.Now().Sub(startTime)//Since返回從t到現在經過的時間,等價于time.Now().Sub(t)。//elapsedTime := time.Since(start)fmt.Println("耗時:", elapsedTime) // 3.278499042s }總結
以上是生活随笔為你收集整理的Golang——时间日期函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux 不知道root密码怎么办,l
- 下一篇: html循环查询的数据,SQL查询遍历数