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
+12.6k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+7.1k Golang : Transform lisp or spinal case to Pascal case example
+11.3k Golang : How to flush a channel before the end of program?
+6k Golang : Create new color from command line parameters
+4.8k Golang : A program that contain another program and executes it during run-time
+15.1k Golang : Save(pipe) HTTP response into a file
+25.8k Golang : How to read integer value from standard input ?
+5.2k PHP : See installed compiled-in-modules
+16.7k Golang : Get own process identifier
+8.2k Golang : HttpRouter multiplexer routing example
+11.1k Golang : Fix - does not implement sort.Interface (missing Len method)
+11.1k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example