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
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"