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.4k Golang : How to get URL port?
+5.3k Golang : Convert Chinese UTF8 characters to Pin Yin
+19.3k Golang : Read directory content with os.Open
+4.7k Golang : What is StructTag and how to get StructTag's value?
+9k Golang : List available AWS regions
+15.5k Golang : Send email and SMTP configuration example
+11.5k Golang : Forwarding a local port to a remote server example
+4.1k Golang : Calculate a pip value and distance to target profit example
+19.2k nginx: [emerg] unknown directive "passenger_enabled"
+6.9k Golang : Test if an input is an Armstrong number example
+9.5k Golang : Meaning of omitempty in struct's field tag
+6.7k Javascript : Push notifications to browser with Push.js