distance_of_time_in_words
很棒,但有时不够精细。
我需要一个能够以文字报告准确时间距离的函数。例如,上午 7:50 到上午 10:10 的距离应该是“2 小时 20 分钟”,而不是“大约 2 小时”或其他什么distance_of_time_in_words
会做。
我的用例是报告火车时刻表,特别是给定的火车行程需要多长时间。
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)