nickolay.laptev
nickolay.laptev

Reputation: 2565

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:

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

How can I do this in Go?

Upvotes: 2

Views: 3180

Answers (3)

wasmup
wasmup

Reputation: 16233

Package time provides Abs functionality since Go1.19:

// Abs returns the absolute value of d.
// As a special case, math.MinInt64 is converted to math.MaxInt64.
func (d Duration) Abs() Duration {
    switch {
    case d >= 0:
        return d
    case d == minDuration:
        return maxDuration
    default:
        return -d
    }
}

Example:

package main

import (
    "fmt"
    "time"
)

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

Try this (without using new Abs() from time package):

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
}

Upvotes: 3

blackgreen
blackgreen

Reputation: 44697

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
}

Upvotes: 5

Fernando Silva
Fernando Silva

Reputation: 1

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

Upvotes: 0

Related Questions