Rails-以小时、分钟和秒为单位获得时差。

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (13)

我正在寻找一种惯用的方式,以小时,分钟和秒钟的方式获得特定日期后的时间。

如果给定的日期是2013-10-25 23:55:00并且当前日期是2013-10-27 20:55:09,则返回值应该是45:03:09。

提问于
用户回答回答于

你可以试试这个:

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"
用户回答回答于
time_diff = Time.now - 2.minutes.ago
Time.at(time_diff.to_i.abs).utc.strftime "%H:%M:%S"
=> "00:01:59"

或者,如果你的应用程序对四舍五入很挑剔,只需将to_i替换为四舍五入:

  Time.at(time_diff.round.abs).utc.strftime "%H:%M:%S"
   => => "00:02:00"

更新:如果时差预计超过24小时,则上述代码不正确。如果是这种情况,可以按照@MrYoshiji的答案或者调整上面的解决方案来手动计算日期时间对象的小时数:

def test_time time_diff
  time_diff = time_diff.round.abs
  hours = time_diff / 3600

  dt = DateTime.strptime(time_diff.to_s, '%s').utc
  "#{hours}:#{dt.strftime "%M:%S"}"
end

test_time Time.now - 28.hours.ago - 2.minutes - 12.seconds
=> "27:57:48" 
test_time Time.now - 8.hours.ago - 2.minutes - 12.seconds
=> "7:57:48" 
test_time Time.now - 24.hours.ago - 2.minutes - 12.seconds
=> "23:57:48" 
test_time Time.now - 25.hours.ago - 2.minutes - 12.seconds
=> "24:57:48" 

扫码关注云+社区