當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。