分钟和秒为单位的时差

分钟和秒为单位的时差

本文介绍了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_differencetime_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"

这篇关于Rails - 获取以小时、分钟和秒为单位的时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 12:45