gpt4 book ai didi

go - 限制持续时间粒度

转载 作者:IT王子 更新时间:2023-10-29 02:06:59 27 4
gpt4 key购买 nike

我通过从当前时间减去保存的时间来计算持续时间:time.Now().Sub(oldTime)

打印它给了我这个:1m30.789260489s

1m30.79s 看起来会更好,我正在使用它。我如何截断/减少 Go 中 Duration 的粒度?

最佳答案

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.


time.Duration 上使用 RoundTruncate 方法。


例如,

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

输出:

1m30.789260489s
1m30.79s

关于go - 限制持续时间粒度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55885290/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com