Home > Backend Development > Golang > How to Convert Go's time.Now().UnixNano() to Milliseconds?

How to Convert Go's time.Now().UnixNano() to Milliseconds?

Susan Sarandon
Release: 2024-12-14 15:03:20
Original
957 people have browsed it

How to Convert Go's time.Now().UnixNano() to Milliseconds?

Converting Go's time.Now().UnixNano() to Milliseconds

The Go programming language provides several useful functions for handling time, including time.Now().UnixNano(), which returns the current timestamp with nanosecond precision. However, you may encounter situations where you only need millisecond precision.

Solution for Go v1.17 and Later

For Go versions 1.17 and above, the time package offers two new functions that simplify this task:

  • time.Now().UnixMicro(): Returns the timestamp with microsecond precision (six digits after the decimal point).
  • time.Now().UnixMilli(): Returns the timestamp with millisecond precision (three digits after the decimal point).

To get the millisecond timestamp, simply use the UnixMilli() method:

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

Solution for Go v1.16 and Earlier

For Go versions 1.16 and earlier, you can achieve the desired conversion manually. Since a millisecond is equivalent to 1,000,000 nanoseconds, you can divide the nanosecond timestamp by 1,000,000:

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

This will give you the millisecond timestamp with three digits after the decimal point.

Example

To demonstrate the usage of these approaches, here's an example you can run:

package main

import (
    "fmt"
    "time"
)

func main() {
    nanoTime := time.Now().UnixNano()
    microTime := time.Now().UnixMicro()
    milliTime := time.Now().UnixMilli()

    fmt.Println("Nano time:", nanoTime)
    fmt.Println("Micro time:", microTime)
    fmt.Println("Milli time:", milliTime)
}
Copy after login

Running this code will output the timestamps with nanosecond, microsecond, and millisecond precision respectively.

The above is the detailed content of How to Convert Go's time.Now().UnixNano() 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