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
+28.2k Golang : How to redirect to new page with net/http?
+14.1k Golang : File path independent of Operating System
+15.5k Golang : How to get own program name during runtime ?
+39.4k Golang : Use wildcard patterns with filepath.Glob() example
+5.6k Android Studio : AlertDialog to get user attention example
+17.6k Golang : Delete item from slice based on index/key position
+11.4k Golang : Verify token from Google Authenticator App
+10.1k Golang : Get terminal width and height example
+17.7k Golang : Append content to a file
+3.7k PHP : See installed compiled-in-modules
+20.4k Golang : Calculate time different
+14.7k Golang : Put UTF8 text on OpenCV video capture image frame