Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current system time in milliseconds

Tags:

ruby

In Ruby, what is the right way to get the current system time since epoch(1970) in milliseconds?

I tried Time.now.to_i , it seems not the result I want. I need the result shows milliseconds and with long type, not float or double.

like image 908
Leem.fin Avatar asked Sep 06 '16 08:09

Leem.fin


2 Answers

(Time.now.to_f * 1000).to_i

Time.now.to_f shows you the time including decimal numbers. To get number of miliseconds just multiply the time by 1000.

like image 199
jan.zikan Avatar answered Oct 24 '22 07:10

jan.zikan


You can combine to_i and usec. The former returns the number of seconds since the Epoch, the latter returns the number of microseconds:

require 'time'
t = Time.at(1473152006, 2000)

t.to_i * 1000 + t.usec / 1000
#=> 1473152006002

This is equivalent to:

t.strftime('%s%L')
#=> "1473152006002"

In some cases like the above, to_f would introduce a slight floating point error:

t.to_f * 1000
#=> 1473152006001.9998
(t.to_f * 1000).to_i
#=> 1473152006001
like image 33
Stefan Avatar answered Oct 24 '22 07:10

Stefan