Tôi đã đưa ra một thực hiện thay thế cho điều này khi được sử dụng trong kịch bản nhật ký ở đây [sao chép từ đó]:
How to generate a human readable time range using ruby on rails
Nếu bạn muốn hiển thị khoảng thời gian đáng kể trong giây để phạm vi ngày, một sự thay thế sẽ là (vì nó không phải thực hiện tốt nhất):
def human_duration(secs, significant_only = true)
n = secs.round
parts = [60, 60, 24, 0].map{|d| next n if d.zero?; n, r = n.divmod d; r}.
reverse.zip(%w(d h m s)).drop_while{|n, u| n.zero? }
if significant_only
parts = parts[0..1] # no rounding, sorry
parts << '0' if parts.empty?
end
parts.flatten.join
end
start = Time.now
# perform job
puts "Elapsed time: #{human_duration(Time.now - start)}"
human_duration(0.3) == '0'
human_duration(0.5) == '1s'
human_duration(60) == '1m0s'
human_duration(4200) == '1h10m'
human_duration(3600*24) == '1d0h'
human_duration(3600*24 + 3*60*60) == '1d3h'
human_duration(3600*24 + 3*60*60 + 59*60) == '1d3h' # simple code, doesn't round
human_duration(3600*24 + 3*60*60 + 59*60, false) == '1d3h59m0s'
Hoặc bạn có thể chỉ quan tâm đến việc tước phần giây khi không quan trọng (cũng chứng minh một cách tiếp cận khác):
def human_duration(duration_in_seconds)
n = duration_in_seconds.round
parts = []
[60, 60, 24].each{|d| n, r = n.divmod d; parts << r; break if n.zero?}
parts << n unless n.zero?
pairs = parts.reverse.zip(%w(d h m s)[-parts.size..-1])
pairs.pop if pairs.size > 2 # do not report seconds when irrelevant
pairs.flatten.join
end
Hy vọng điều đó sẽ hữu ích.
bây giờ tôi biết Ruby hơn. .. có thể một 'Time.now.how_long_since start' hoặc' Time.now.duration_since start' có thể thanh lịch hơn? –