HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
millisecondstimenowconvertunixnano

Problem

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.

Solution

The 2021 answer:

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

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
}

Code Snippets

func makeTimestamp() int64 {
    return time.Now().UnixNano() / 1e6
}
package main

import (
    "time"
    "fmt"
)

func main() {
    a := makeTimestamp()

    fmt.Printf("%d \n", a)
}

func makeTimestamp() int64 {
    return time.Now().UnixNano() / 1e6
}

Context

Stack Overflow Q#24122821, score: 235

Revisions (0)

No revisions yet.