Go語言借助時間包為測量和顯示時間提供了內置支持。在此程序包中,日曆計算始終采用公曆,沒有with秒。該軟件包提供了一個ParseDuration()函數,該函數可以解析持續時間字符串。持續時間字符串是帶符號的十進製數字序列,帶有可選的分數和單位後綴,例如“100ms”,“2.3h”或“4h35m”。要訪問ParseDuration()函數,您需要借助import關鍵字在程序中添加時間包。
注意:有效時間單位為“ns”,“us”(或“µs”),“ms”,“s”,“m”,“h”。
用法:
func ParseDuration(str string) (Duration, error)
範例1:
// Golang program to illustrate
// how to find time duration
package main
import (
"fmt"
"time"
)
func main() {
// Using ParseDuration() function
hr, _:= time.ParseDuration("3h")
comp, _:= time.ParseDuration("5h30m40s")
fmt.Println("Time Duration 1:", hr)
fmt.Println("Time Duration 2:", comp)
}
輸出:
Time Duration 1: 3h0m0s Time Duration 2: 5h30m40s
範例2:
// Golang program to illustrate
// how to find time duration
package main
import (
"fmt"
"time"
)
func main() {
// Using ParseDuration() function
hr, _:= time.ParseDuration("5h")
comp, _:= time.ParseDuration("2h30m40s")
m1, _:= time.ParseDuration("3µs")
m2, _:= time.ParseDuration("3us")
fmt.Println("Time Duration 1:", hr)
fmt.Println("Time Duration 2:", comp)
fmt.Printf("There are %.0f seconds in %v.\n",
comp.Seconds(), comp)
fmt.Printf("There are %d nanoseconds in %v.\n",
m1.Nanoseconds(), m1)
fmt.Printf("There are %6.2e seconds in %v.\n",
m2.Seconds(), m1)
}
輸出:
Time Duration 1: 5h0m0s Time Duration 2: 2h30m40s There are 9040 seconds in 2h30m40s. There are 3000 nanoseconds in 3µs. There are 3.00e-06 seconds in 3µs.
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 time.ParseDuration() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。