How can I get Unix time in Go in milliseconds?
I have the following function:
func makeTimestamp() int64 {
return time.Now().UnixNano() % 1e6 / 1e3
}
I need less precision and only want milliseconds.
As of go v1.17, the time
package added UnixMicro()
and UnixMilli()
, so the correct answer would be: time.Now().UnixMilli()
Just divide it:
func makeTimestamp() int64 {
return time.Now().UnixNano() / 1e6
}
1e6
, i.e. 1 000 000, is the number of nanoseconds in a millisecond.
Here is an example that you can compile and run to see the output
package main
import (
"time"
"fmt"
)
func main() {
a := makeTimestamp()
fmt.Printf("%d \n", a)
}
func makeTimestamp() int64 {
return time.Now().UnixNano() / 1e6
}