简体   繁体   English

time.Duration 之间的绝对差异

[英]Absolute difference between time.Duration

I have 2 variables with time.Duration type.我有 2 个time.Duration类型的变量。 I need to find the difference in duration between them.我需要找到它们之间的持续时间差异。

For example:例如:

  • v1 = 1sec and v2 = 10sec — difference is 9 sec. v1 = 1 秒和 v2 = 10 秒——相差 9 秒。
  • v1 = 10sec and v2 = 1sec — difference is also 9 sec. v1 = 10 秒和 v2 = 1 秒 — 差异也是 9 秒。

Both variables can have different values for hours, minutes etc.两个变量可以有不同的小时、分钟等值。

How can I do this in Go?如何在 Go 中做到这一点?

Try this:尝试这个:

package main

import (
    "fmt"
    "time"
)

func main() {
    a := 1 * time.Second
    b := 10 * time.Second
    c := absDiff(a, b)
    fmt.Println(c)         // 9s
    fmt.Println(absDiff(b, a)) // 9s

}
func absDiff(a, b time.Duration) time.Duration {
    if a >= b {
        return a - b
    }
    return b - a
}

This is another form:这是另一种形式:

package main

import (
    "fmt"
    "time"
)

func main() {
    a := 1 * time.Second
    b := 10 * time.Second
    c := abs(a - b)
    fmt.Println(c) // 9s
}

func abs(a time.Duration) time.Duration {
    if a >= 0 {
        return a
    }
    return -a
}

Go 1.19 Go 1.19

The function Abs has been added to the language, so you can just use that instead of rolling your own: function Abs已添加到该语言中,因此您可以使用它而不是自己滚动:

func main() {
    d1 := time.Second * 10
    d2 := time.Second

    sub1 := d1 - d2
    sub2 := d2 - d1

    fmt.Println(sub1.Abs()) // 9s
    fmt.Println(sub2.Abs()) // 9s
}

An elegant solution is to use bitshift >>一个优雅的解决方案是使用 bitshift >>

func absDuration(d time.Duration) time.Duration {
   s := d >> 63 
   return (d ^ s) - s
}

bitshift in Golang is logic if the left operand is negative如果左操作数为负,Golang 中的位移是逻辑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM