Golang : How to get time in milliseconds?
Helping out a friend to calculate millisecond from a given date today. Apparently, there is no direct function in Golang's time package to get milliseconds from time. To get the time in milliseconds, we have to get the nano seconds first and then convert the nano seconds to milliseconds.
Below is a note from our experiment in getting time in milliseconds with Golang. Hope this short tutorial may be useful to you.
Here you go!
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("Today : ", now.Format(time.ANSIC))
// wrong way to convert nano to millisecond
nano := now.Nanosecond()
millisec := nano / 1000000
fmt.Println("(wrong)Millisecond : ", millisec)
// correct way to convert time to millisecond - with UnixNano()
unixNano := now.UnixNano()
umillisec := unixNano / 1000000
fmt.Println("(correct)Millisecond : ", umillisec)
}
Reference :
https://socketloop.com/references/golang-time-time-nanosecond-function-example
Sample output :
Today : Mon Aug 17 13:14:02 2015
(wrong)Millisecond : 681
(correct)Millisecond : 1439788442681
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+29.4k Golang : JQuery AJAX post data to server and send data back to client example
+13.6k Golang : Query string with space symbol %20 in between
+19.9k Golang : Measure http.Get() execution time
+9.5k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+16.8k Golang : Get own process identifier
+19.6k Golang : Close channel after ticker stopped example
+4.6k MariaDB/MySQL : How to get version information
+8.2k Golang : Find relative luminance or color brightness
+31.5k Golang : bufio.NewReader.ReadLine to read file line by line
+24.1k Golang : Find biggest/largest number in array
+6.3k WARNING: UNPROTECTED PRIVATE KEY FILE! error message
+6k PHP : How to check if an array is empty ?