Home >Backend Development >Golang >How to Get the Unix Timestamp in Milliseconds Using Go?

How to Get the Unix Timestamp in Milliseconds Using Go?

Linda Hamilton
Linda HamiltonOriginal
2024-12-15 17:06:14187browse

How to Get the Unix Timestamp in Milliseconds Using Go?

Question: How can I obtain the Unix timestamp in milliseconds in Go?

Explanation:

The current Go function that retrieves the Unix timestamp, time.Now().UnixNano(), provides a value in nanoseconds. However, your requirement specifies converting this value to milliseconds.

Answer:

Currently, the time package in Go provides two convenient functions:

  • UnixMicro() for converting to microseconds
  • UnixMilli() for converting to milliseconds

Therefore, for Go versions 1.17 and later, the recommended solution is:

timestamp := time.Now().UnixMilli()

For Go versions 1.16 and earlier:

You can divide the nanosecond timestamp by 1e6, which represents the number of nanoseconds in a millisecond:

timestamp := time.Now().UnixNano() / 1e6

The above is the detailed content of How to Get the Unix Timestamp in Milliseconds Using Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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