Tom*_*man 13 time ruby-on-rails
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
Run Code Online (Sandbox Code Playgroud)