Rails - 获取小时,分钟和秒的时差

26 ruby ruby-on-rails ruby-on-rails-3 ruby-2.0 ruby-on-rails-4

我正在寻找一种惯用的方法来获取自给定日期以小时,分钟和秒为单位的时间.

如果给定日期是2013-10-25 23:55:00,当前日期是2013-10-27 20:55:09,则返回值应为45:03:09.该TIME_DIFFERENCEtime_diff宝石不会与此要求的工作.

MrY*_*iji 39

你可以尝试这个:

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
Run Code Online (Sandbox Code Playgroud)

并使用它:

time_diff(Time.now, Time.now-2.days-3.hours-4.minutes-5.seconds)
# => "51:04:04"
Run Code Online (Sandbox Code Playgroud)


Tum*_*mas 28

time_diff = Time.now - 2.minutes.ago
Time.at(time_diff.to_i.abs).utc.strftime "%H:%M:%S"
=> "00:01:59"
Run Code Online (Sandbox Code Playgroud)

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

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

虽然不确定惯用的部分

更新:如果预计时差超过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" 
Run Code Online (Sandbox Code Playgroud)

  • 这是非常干净的,但它永远不会返回过去24小时. (2认同)

Fra*_*ois 7

有一种方法:

Time.now.minus_with_coercion(10.seconds.ago)

等于10(事实上,9.99 ......,.round如果你想要10则使用).

资料来源:http://apidock.com/rails/Time/minus_with_coercion

希望我帮忙.