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
+13.3k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+12.3k Golang : Split strings into command line arguments
+8.4k Golang : Configure Apache and NGINX to access your Go service example
+26.6k Golang : Convert(cast) string to uint8 type and back to string
+7.2k Golang : Get environment variable
+10.6k Swift : Convert (cast) String to Integer
+18k Golang : Iterate linked list example
+11.8k Golang : Convert(cast) float to int
+10k Random number generation with crypto/rand in Go
+10.1k Golang : Read file and convert content to string
+18.9k Golang : Delete duplicate items from a slice/array
+9.7k Golang : Quadratic example