Home > Backend Development > Golang > How Do I Get the Current Unix Time in Milliseconds Using Go?

How Do I Get the Current Unix Time in Milliseconds Using Go?

DDD
Release: 2024-12-10 08:21:10
Original
654 people have browsed it

How Do I Get the Current Unix Time in Milliseconds Using Go?

Get Unix Time in Milliseconds with Go's time.Now().UnixNano()

In Go, the time.Now().UnixNano() function provides a high-precision timestamp in nanosecond resolution. To obtain milliseconds instead, a simple conversion is necessary.

For Go v1.17 and Later:

In Go versions 1.17 and above, the time package conveniently introduced the UnixMicro() and UnixMilli() methods. To get the timestamp in milliseconds:

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

For Go v1.16 and Earlier:

For earlier Go versions, division by 1e6 (1 million) can be used to convert from nanoseconds to milliseconds:

milliseconds := time.Now().UnixNano() / 1e6
Copy after login

For example:

import (
    "time"
    "fmt"
)

func main() {
    ms := time.Now().UnixNano() / 1e6
    fmt.Println(ms) // Output: 1665376382059
}
Copy after login

The above is the detailed content of How Do I Get the Current Unix Time in Milliseconds Using Go?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template