当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


GO ParseDuration用法及代码示例


GO语言"time"包中"ParseDuration"函数的用法及代码示例。

用法:

func ParseDuration(s string)(Duration, error)

ParseDuration 解析持续时间字符串。持续时间字符串是可能有符号的十进制数字序列,每个数字都有可选的分数和单位后缀,例如"300ms"、"-1.5h" 或"2h45m"。有效时间单位为"ns"、"us"(或"µs")、"ms"、"s"、"m"、"h"。

例子:

package main

import (
	"fmt"
	"time"
)

func main() {
	hours, _ := time.ParseDuration("10h")
	complex, _ := time.ParseDuration("1h10m10s")
	micro, _ := time.ParseDuration("1µs")
	// The package also accepts the incorrect but common prefix u for micro.
	micro2, _ := time.ParseDuration("1us")

	fmt.Println(hours)
	fmt.Println(complex)
	fmt.Printf("There are %.0f seconds in %v.\n", complex.Seconds(), complex)
	fmt.Printf("There are %d nanoseconds in %v.\n", micro.Nanoseconds(), micro)
	fmt.Printf("There are %6.2e seconds in %v.\n", micro2.Seconds(), micro)
}

输出:

10h0m0s
1h10m10s
There are 4210 seconds in 1h10m10s.
There are 1000 nanoseconds in 1µs.
There are 1.00e-06 seconds in 1µs.

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 ParseDuration。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。