Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go time.Now().UnixNano() convert to milliseconds?

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.

like image 363
mconlin Avatar asked Jun 09 '14 14:06

mconlin


2 Answers

The 2021 answer:

As of go v1.17, the time package added UnixMicro() and UnixMilli(), so the correct answer would be: time.Now().UnixMilli()

Original answer:

Just divide it:

func makeTimestamp() int64 {     return time.Now().UnixNano() / int64(time.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() / int64(time.Millisecond) } 
like image 161
OneOfOne Avatar answered Nov 01 '22 16:11

OneOfOne


As @Jono points out in @OneOfOne's answer, the correct answer should take into account the duration of a nanosecond. Eg:

func makeTimestamp() int64 {     return time.Now().UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond)) } 

OneOfOne's answer works because time.Nanosecond happens to be 1, and dividing by 1 has no effect. I don't know enough about go to know how likely this is to change in the future, but for the strictly correct answer I would use this function, not OneOfOne's answer. I doubt there is any performance disadvantage as the compiler should be able to optimize this perfectly well.

See https://en.wikipedia.org/wiki/Dimensional_analysis

Another way of looking at this is that both time.Now().UnixNano() and time.Millisecond use the same units (Nanoseconds). As long as that is true, OneOfOne's answer should work perfectly well.

like image 35
Bjorn Roche Avatar answered Nov 01 '22 16:11

Bjorn Roche