I have this jQuery
function that returns the current time as the number of milliseconds since the epoch (Jan 1, 1970):
time = new Date().getTime();
Is there a way to do the same in Ruby?
Right now, I am using Ruby's Time.now.to_i
which works great but returns a 10-digit integer (number of seconds)
How can I get it to display the number of milliseconds, as in jQuery
?
now() is used to get the present time. The timetuple() is a method of datetime class that returns the attributes of datetime as a name tuple. To get the timestamp of 13 digits it has to be multiplied by 1000.
10 digit epoch time format surrounded by brackets (or followed by a comma). The digits must be at the very start of the message.
require 'date' p DateTime.now.strftime('%s') # "1384526946" (seconds) p DateTime.now.strftime('%Q') # "1384526946523" (milliseconds)
Javascript's gettime()
returns the number of milliseconds since epoch.
Ruby's Time.now.to_i
will give you the number of seconds since epoch. If you change that to Time.now.to_f
, you still get seconds but with a fractional component. Just multiply that by 1,000 and you have milliseconds. Then use #to_i
to convert it to an integer. And you end up with:
(Time.now.to_f * 1000).to_i
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