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
.
(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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With