dsfs23434 2019-04-27 22:11
浏览 30
已采纳

限制持续时间粒度

I've calculated a Duration by subtracting a saved time from the current time: time.Now().Sub(oldTime)

Printing it gives me this: 1m30.789260489s

1m30.79s would look better, where I'm using it. How can I truncate / reduce the granularity of a Duration in Go?

  • 写回答

1条回答 默认 最新

  • dpdrtj1075 2019-04-27 22:14
    关注

    Package time

    import "time"
    

    func (Duration) Round 1.9

    func (d Duration) Round(m Duration) Duration

    Round returns the result of rounding d to the nearest multiple of m. The rounding behavior for halfway values is to round away from zero. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, Round returns the maximum (or minimum) duration. If m <= 0, Round returns d unchanged.

    func (Duration) Truncate 1.9

    func (d Duration) Truncate(m Duration) Duration

    Truncate returns the result of rounding d toward zero to a multiple of m. If m <= 0, Truncate returns d unchanged.


    Use the Round or Truncate methods on the time.Duration.


    For example,

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        d, err := time.ParseDuration("1m30.789260489s")
        if err != nil {
            panic(err)
        }
        fmt.Println(d)
        fmt.Println(d.Round(10 * time.Millisecond))
    }
    

    Playground: https://play.golang.org/p/8b3xAxfSE90

    Output:

    1m30.789260489s
    1m30.79s
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥85 maple软件,solve求反函数,出现rootof怎么办?
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题