Using strftime , you can get the number of seconds and add fractional milliseconds (or, if necessary, smaller units):
2.2.2 :001 > t = Time.new => 2015-06-02 12:16:56 -0700 2.2.2 :002 > t.strftime('%s%3N') => "1433272616888"
Note that this is not cool, it is truncated, as you can see with to_f , or if you go out in microseconds:
2.2.2 :003 > t.to_f => 1433272616.888615 2.2.2 :004 > t.usec => 888615
and the solution to_f / to_i has the same problem:
2.2.2 :009 > (t.to_f * 1000).to_i => 1433272616888
therefore, if you really need precision in milliseconds, it is better to bet to_f with round :
2.2.2 :010 > (t.to_f * 1000).round => 1433272616889
However, as noted in the docs , "the dual IEEE 754 is not accurate enough to represent the number of nanoseconds since the era," so if you really pay attention to_r instead of to_f -
2.2.2 :011 > (t.to_r * 1000).round => 1433272616889
- although if you only round to the millisecond, you are probably fine.
David Moles Jun 02 '15 at 7:28 2015-06-02 19:28
source share