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.
For Go versions 1.17 and above, the time package offers two new functions that simplify this task:
To get the millisecond timestamp, simply use the UnixMilli() method:
timeMs := time.Now().UnixMilli()
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
This will give you the millisecond timestamp with three digits after the decimal point.
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) }
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!