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

后端 未结 7 483
闹比i
闹比i 2020-12-04 11:35

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         


        
7条回答
  •  我在风中等你
    2020-12-04 12:26

    Using strftime, you can get the number of seconds and append fractional milliseconds (or smaller units, if needed):

    2.2.2 :001 > t = Time.new
     => 2015-06-02 12:16:56 -0700 
    2.2.2 :002 > t.strftime('%s%3N')
     => "1433272616888" 
    

    Note though that this doesn't round, it truncates, as you can see with to_f or if you go out to microseconds:

    2.2.2 :003 > t.to_f
     => 1433272616.888615
    2.2.2 :004 > t.usec
     => 888615 
    

    and the to_f / to_i solution has the same problem:

    2.2.2 :009 > (t.to_f * 1000).to_i
     => 1433272616888
    

    so if you really care about millisecond accuracy, a better bet may be to_f with round:

    2.2.2 :010 > (t.to_f * 1000).round
     => 1433272616889
    

    That said, as noted in the docs, "IEEE 754 double is not accurate enough to represent the number of nanoseconds since the Epoch", so if you really really care, consider to_r instead of to_f --

    2.2.2 :011 > (t.to_r * 1000).round
     => 1433272616889 
    

    -- although if you're only rounding to milliseconds you're probably fine.

提交回复
热议问题