Go 语言在time 包的帮助下为测量和显示时间提供了内置支持。在这个包中,日历计算总是假设没有闰秒的公历。这个包提供了一个解析持续时间字符串的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.