更精确的 distance_of_time_in_words [英] More precise distance_of_time_in_words
本文介绍了更精确的 distance_of_time_in_words的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
distance_of_time_in_words
很棒,但有时不够细化.
distance_of_time_in_words
is great, but sometimes it's not granular enough.
我需要一个能用文字报告确切时间距离的函数.例如,上午 7:50 到上午 10:10 的距离应该是2 小时 20 分钟",而不是大约 2 小时"或 distance_of_time_in_words
会做的任何事情.
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
这篇关于更精确的 distance_of_time_in_words的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文