Home > Backend Development > Golang > How to Convert Go's UnixNano Timestamp to Milliseconds?

How to Convert Go's UnixNano Timestamp to Milliseconds?

Susan Sarandon
Release: 2024-12-09 21:22:17
Original
147 people have browsed it

How to Convert Go's UnixNano Timestamp to Milliseconds?

Converting Go's UnixNano to Milliseconds

In Go, the time.Now().UnixNano() function provides a timestamp with nanosecond precision. To obtain the timestamp in milliseconds, you can perform the necessary conversion.

For Go v1.17 and Later:

As of Go v1.17, the time package includes the UnixMicro() and UnixMilli() functions, making the conversion straightforward:

timestamp := time.Now().UnixMilli()
Copy after login

For Go v1.16 and Earlier:

Prior to Go v1.17, you can convert the nanosecond timestamp to milliseconds using division:

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

Here, 1e6 represents the number of nanoseconds in a millisecond.

Below is a sample program that demonstrates the conversion:

package main

import (
    "fmt"
    "time"
)

func main() {
    timestamp := makeTimestamp()

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

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

The above is the detailed content of How to Convert Go's UnixNano Timestamp to Milliseconds?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template