How do I get the number of seconds between two DateTimes in Ruby on Rails

后端 未结 8 1743
庸人自扰
庸人自扰 2020-12-23 15:37

I\'ve got code that does time tracking for employees. It creates a counter to show the employee how long they have been clocked in for.

This is the current code:

相关标签:
8条回答
  • 2020-12-23 16:36

    Or, more readably:

    diff = datetime_1 - datetime_2
    diff * 1.days # => difference in seconds; requires Ruby on Rails
    

    Note, what you or some other searchers might really be looking for is this:

    diff = datetime_1 - datetime_2
    Date.day_fraction_to_time(diff) # => [h, m, s, frac_s]
    
    0 讨论(0)
  • 2020-12-23 16:39

    You can convert them to floats with to_f, though this will incur the usual loss of precision associated with floats. If you're just casting to an integer for whole seconds it shouldn't be big enough to be a worry.

    The results are in seconds:

    >> end_time.to_f - start_time.to_f
    => 7.39954495429993
    
    >> (end_time.to_f - start_time.to_f).to_i
    => 7
    

    Otherwise, you could look at using to_formatted_s on the DateTime object and seeing if you can coax the output into something the Decimal class will accept, or just formatting it as plain Unix time as a string and calling to_i on that.

    0 讨论(0)
提交回复
热议问题