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

后端 未结 8 1742
庸人自扰
庸人自扰 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:21

    Subtracting two DateTimes returns the elapsed time in days, so you could just do:

    elapsed_seconds = ((end_time - start_time) * 24 * 60 * 60).to_i
    
    0 讨论(0)
  • 2020-12-23 16:21

    I am using ruby-2.1.4 and for me the following worked

    Time.now - Time.new(2014,11,05,17,30,0)
    

    gave me the time difference in seconds

    reference: ruby doc

    0 讨论(0)
  • 2020-12-23 16:24

    there's a method made for that:

    Time.now.minus_with_coercion(10.seconds.ago)

    equals 10.

    Source: http://apidock.com/rails/Time/minus_with_coercion

    Hope I helped.

    0 讨论(0)
  • 2020-12-23 16:25

    Define a Ruby function like this,

    def time_diff(start_time, end_time)
      seconds_diff = (start_time - end_time).to_i.abs
    
      days = seconds_diff / 86400 
      seconds_diff -= days * 86400
    
      hours = seconds_diff / 3600  
      seconds_diff -= hours * 3600
    
      minutes = seconds_diff / 60
      seconds_diff -= minutes * 60
    
      seconds = seconds_diff
    
      "#{days} Days #{hours} Hrs #{minutes} Min #{seconds} Sec"
     end
    

    And Call this function,

    time_diff(Time.now, Time.now-4.days-2.hours-1.minutes-53.seconds)
    
    0 讨论(0)
  • 2020-12-23 16:34

    Others incorrectly rely on fractions or helper functions. It's much simpler than that. DateTime itself is integer underneath. Here's the Ruby way:

    stop.to_i - start.to_i
    

    Example:

    start = Time.now
     => 2016-06-21 14:55:36 -0700
    stop = start + 5.seconds
     => 2016-06-21 14:55:41 -0700
    stop.to_i - start.to_i
     => 5
    
    0 讨论(0)
  • 2020-12-23 16:34

    why not use the built in "sec" . Here is an example :

    t1 = Time.now.sec 
    
    elapsed_t = Time.now.sec - t1
    
    puts "it took me :  #{elapsed_t} seconds to do something that is useful \n"
    
    0 讨论(0)
提交回复
热议问题