Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current time as 13-digit integer in Ruby?

Tags:

ruby

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?

like image 246
Tintin81 Avatar asked Oct 30 '12 23:10

Tintin81


People also ask

How do you find the 13 digit timestamp in python?

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.

How many digits is a timestamp?

10 digit epoch time format surrounded by brackets (or followed by a comma). The digits must be at the very start of the message.


2 Answers

require 'date'  p DateTime.now.strftime('%s') # "1384526946" (seconds) p DateTime.now.strftime('%Q') # "1384526946523" (milliseconds) 
like image 77
steenslag Avatar answered Oct 09 '22 21:10

steenslag


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 
like image 35
Anthony DeSimone Avatar answered Oct 09 '22 22:10

Anthony DeSimone