GO 時間和日期函式

2021-10-07 21:18:10 字數 2113 閱讀 7297

介紹:

在程式設計中,經常使用到的日期相關的函式

時間和日期相關函式,需要匯入time包 包:

time.time型別,用於獲取當前時間

package main

import

("fmt"

"time"

)func

main()

用於獲取詳細的年月日時分秒

package main

import

("fmt"

"time"

)func

main()

格式化日期時間

方式一

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

休眠:func sleep(d duration) 結合sleep來使用一下時間常量

package main

import

("fmt"

"time"

)func

main()

}}

獲取當前unix時間戳 和 unixnano 時間戳(作用是可以獲取隨機數)

unix:返回2023年至今的秒數

unixnano:返回2023年至今的納秒數

例項:編寫一段**來統計,函式test03執行的時間

package main

import

("fmt"

"strconv"

"time"

)func

test01()

}func

main()

go時間和日期

時間和日期相差的操作在time包中 獲取當前時間 now time.now 返回的是time型別 time now.format 2006 1 2 3 4 5 格式化為string 這個引數是固定的 go誕生的時間 hour 60 minute 1小時 60分鐘 minute 60 second 1...

go時間和日期

1.time包 2.time.time型別,用來表示時間 3.獲取當前時間,now time.now 4.time.now day time.now minute time.now month time.now year 5.格式化,fmt.printf 02d 02d 02d 02d 02d 02...

go語言時間和日期相關函式

時間和日期相關得函式,需要匯入time包 time包提供了時間和日期顯示的相關函式,日曆的計算採用的時公曆 time.time 用於表示時間 func main 結果 3.獲取其它的日期資訊 package main import fmt time func main 結果 格式化日期時間 pack...