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

后端 未结 7 471
闹比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:34

    Be careful, don't get confused. The fact that Ruby supports the idea of fractional seconds as a float doesn't actually make it a floating point number. I got into trouble with this when I was doing Wireshark timestamp time comparisons in Python... the time calculations in the pcap-ng just weren't working. It was only when I treated the two parts (integral seconds and integral nanoseconds) as both integers was I able to get proper numbers.

    That's because floating point numbers have Accuracy problems. Indeed, a quick bit of Ruby will show you that to_f does not equal, say, nsec:

    irb(main):019:0> t=Time.now
    => 2015-04-10 16:41:35 -0500
    irb(main):020:0> puts "#{t.to_f}; #{t.nsec}"
    1428702095.1435847; 143584844
    

    Caveat Programmer. You may be safe to 3 significant digits, but the fact remains: Floating point numbers on computers are approximations. The nanosecond counters on modern computers are integers.

提交回复
热议问题