Home >Backend Development >Golang >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()
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 }
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 }
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!