Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More precise distance_of_time_in_words

distance_of_time_in_words is great, but sometimes it's not granular enough.

I need a function that will report exact distances of time in words. E.g., 7:50AM to 10:10AM should be a distance of "2 hours and 20 minutes", not "about 2 hours" or whatever distance_of_time_in_words would do.

My use case is reporting train schedules, and in particular how long a given train ride will take.

like image 673
Tom Lehman Avatar asked Aug 03 '09 21:08

Tom Lehman


1 Answers

def distance_of_time_in_hours_and_minutes(from_time, to_time)
  from_time = from_time.to_time if from_time.respond_to?(:to_time)
  to_time = to_time.to_time if to_time.respond_to?(:to_time)
  distance_in_hours   = (((to_time - from_time).abs) / 3600).floor
  distance_in_minutes = ((((to_time - from_time).abs) % 3600) / 60).round

  difference_in_words = ''

  difference_in_words << "#{distance_in_hours} #{distance_in_hours > 1 ? 'hours' : 'hour' } and " if distance_in_hours > 0
  difference_in_words << "#{distance_in_minutes} #{distance_in_minutes == 1 ? 'minute' : 'minutes' }"
end
like image 141
Michael Sepcot Avatar answered Oct 13 '22 09:10

Michael Sepcot