Absolute difference between time.Duration

Issue

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. The difference will be 9 sec. The same difference will be if v1 = 10sec and v2 = 1sec.
Both variables can have different values for hours, minutes etc.

How can I do this in Go?

This is a trivial question but I’m new to Go.

Solution:
I used a modified version of provided answer:

func abs(value time.Duration) time.Duration {
    if value < 0 {
        return -value
    }
    return value
}

Solution

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
}

Answered By – wasmup

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.