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
+15.8k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+7.7k SSL : How to check if current certificate is sha1 or sha2 from command line
+16.5k Golang : convert string or integer to big.Int type
+10.4k Golang : Wait and sync.WaitGroup example
+18.9k Unmarshal/Load CSV record into struct in Go
+24.7k Golang : GORM read from database example
+10.1k Golang : Sort and reverse sort a slice of integers
+4.8k MariaDB/MySQL : How to get version information
+13.8k Golang : Strings comparison
+6.2k Golang : Experimenting with the Rejang script
+8.4k Golang : Oanda bot with Telegram and RSI example
+8.4k Golang : HttpRouter multiplexer routing example