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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With