Rails - Get the time difference in hours, minutes and seconds

46,846

Solution 1

You can try with this:

def time_diff(start_time, end_time)
  seconds_diff = (start_time - end_time).to_i.abs

  hours = seconds_diff / 3600
  seconds_diff -= hours * 3600

  minutes = seconds_diff / 60
  seconds_diff -= minutes * 60

  seconds = seconds_diff

  "#{hours.to_s.rjust(2, '0')}:#{minutes.to_s.rjust(2, '0')}:#{seconds.to_s.rjust(2, '0')}"
  # or, as hagello suggested in the comments:
  # '%02d:%02d:%02d' % [hours, minutes, seconds]
end

And use it:

time_diff(Time.now, Time.now-2.days-3.hours-4.minutes-5.seconds)
# => "51:04:04"

Solution 2

time_diff = Time.now - 2.minutes.ago
Time.at(time_diff.to_i.abs).utc.strftime "%H:%M:%S"
=> "00:01:59"

Or if your app is picky about rounding, just replace to_i to round:

  Time.at(time_diff.round.abs).utc.strftime "%H:%M:%S"
   => => "00:02:00"

Not sure about the idiomatic part though

Update: If time difference is expected to be more than 24 hours then the above code is not correct. If such is the case, one could follow the answer of @MrYoshiji or adjust above solution to calculate hours from a datetime object manually:

def test_time time_diff
  time_diff = time_diff.round.abs
  hours = time_diff / 3600

  dt = DateTime.strptime(time_diff.to_s, '%s').utc
  "#{hours}:#{dt.strftime "%M:%S"}"
end

test_time Time.now - 28.hours.ago - 2.minutes - 12.seconds
=> "27:57:48" 
test_time Time.now - 8.hours.ago - 2.minutes - 12.seconds
=> "7:57:48" 
test_time Time.now - 24.hours.ago - 2.minutes - 12.seconds
=> "23:57:48" 
test_time Time.now - 25.hours.ago - 2.minutes - 12.seconds
=> "24:57:48" 

Solution 3

There's a method for that:

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

equals 10 (in fact, 9.99..., use .round if you want a 10).

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

Hope I helped.

Solution 4

Since this has not been marked as duplicate, and the response in the main thread is just way clearer IMHO. I'll add it here for more visibility:

It can be done pretty concisely using divmod:

t = (end_time - start_time).round.abs
mm, ss = t.divmod(60)
hh, mm = mm.divmod(60)
puts "%02d:%02d:%02d" % [hh, mm, ss]

You could probably DRY it further by getting creative with collect, or maybe inject, but when the core logic is three lines it may be overkill.

Note that I've changed a bit the answer to fit better this thread's question.

Share:
46,846
Admin
Author by

Admin

Updated on June 24, 2020

Comments

  • Admin
    Admin almost 4 years

    I'm looking for an idiomatic way to get the time passed since a given date in hours, minutes and seconds.

    If the given date is 2013-10-25 23:55:00 and the current date is 2013-10-27 20:55:09, the returning value should be 45:03:09. The time_difference and time_diff gems won't work with this requirement.