Number to time.Duration
time.Duration
is a type having int64
as its underlying type, which stores the duration in nanoseconds.
If you know the value but you want other than nanoseconds, simply multiply the unit you want, e.g.:
d := 100 * time.Microsecond
fmt.Println(d) // Output: 100µs
The above works because 100
is an untyped constant, and it can be converted automatically to time.Duration
which has int64
underlying type.
Note that if you have the value as a typed value, you have to use explicit type conversion:
value := 100 // value is of type int
d2 := time.Duration(value) * time.Millisecond
fmt.Println(d2) // Output: 100ms
time.Duration
to number
So time.Duration
is always the nanoseconds. If you need it in milliseconds for example, all you need to do is divide the time.Duration
value with the number of nanoseconds in a millisecond:
ms := int64(d2 / time.Millisecond)
fmt.Println("ms:", ms) // Output: ms: 100
Other examples:
fmt.Println("ns:", int64(d2/time.Nanosecond)) // ns: 100000000
fmt.Println("µs:", int64(d2/time.Microsecond)) // µs: 100000
fmt.Println("ms:", int64(d2/time.Millisecond)) // ms: 100
Try the examples on the Go Playground.
If your jitter (duration) is less than the unit you wish to convert it to, you need to use floating point division, else an integer division will be performed which cuts off the fraction part. For details see: Golang Round to Nearest 0.05.
Convert both the jitter and unit to float64
before dividing:
d := 61 * time.Microsecond
fmt.Println(d) // Output: 61µs
ms := float64(d) / float64(time.Millisecond)
fmt.Println("ms:", ms) // Output: ms: 0.061
Output (try it on the Go Playground):
61µs
ms: 0.061