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
+9.2k Mac OSX : Get a process/daemon status information
+6.1k Golang : Test input string for unicode example
+9.1k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+12.9k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+17.5k Golang : Qt image viewer example
+26k Golang : Calculate future date with time.Add() function
+9.4k Golang : Sort and reverse sort a slice of floats
+4.6k Fix Google Analytics Redundant Hostnames problem
+6.5k Golang : Experimental emojis or emoticons icons programming language
+6.5k Golang : Join lines with certain suffix symbol example
+8.7k Golang : Go as a script or running go with shebang/hashbang style
+14.4k Golang : Get URI segments by number and assign as variable example