Rails - 获取以小时、分钟和秒为单位的时差
问题描述:
我正在寻找一种惯用的方法来以小时、分钟和秒为单位获取自给定日期以来经过的时间.
I'm looking for an idiomatic way to get the time passed since a given date in hours, minutes and seconds.
如果给定日期是 2013-10-25 23:55:00,当前日期是 2013-10-27 20:55:09,则返回值应该是 45:03:09.time_difference 和 time_diff 宝石获胜不符合此要求.
If the given date is 2013-10-25 23:55:00 and the current date is 2013-10-27 20:55:09, the returning value should be 45:03:09. The time_difference and time_diff gems won't work with this requirement.
答
你可以试试这个:
def time_diff(start_time, end_time)
seconds_diff = (start_time - end_time).to_i.abs
hours = seconds_diff / 3600
seconds_diff -= hours * 3600
minutes = seconds_diff / 60
seconds_diff -= minutes * 60
seconds = seconds_diff
"#{hours.to_s.rjust(2, '0')}:#{minutes.to_s.rjust(2, '0')}:#{seconds.to_s.rjust(2, '0')}"
# or, as hagello suggested in the comments:
# '%02d:%02d:%02d' % [hours, minutes, seconds]
end
并使用它:
time_diff(Time.now, Time.now-2.days-3.hours-4.minutes-5.seconds)
# => "51:04:04"