'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. 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 1:[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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
