简体   繁体   中英

Absolute difference between time.Duration

I have 2 variables with time.Duration type. I need to find the difference in duration between them.

For example:

  • v1 = 1sec and v2 = 10sec — difference is 9 sec.
  • v1 = 10sec and v2 = 1sec — difference is also 9 sec.

Both variables can have different values for hours, minutes etc.

How can I do this in 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

The function Abs has been added to the language, so you can just use that instead of rolling your own:

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 >>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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