Leem.fin
Leem.fin

Reputation: 42692

Get current system time in milliseconds

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.

Upvotes: 8

Views: 7251

Answers (2)

Stefan
Stefan

Reputation: 114248

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

Upvotes: 7

jan.zikan
jan.zikan

Reputation: 1316

(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.

Upvotes: 10

Related Questions