2017-03-06 87 views
1

我試圖計算我的記錄在Rails 5中的「剩餘時間」。我的記錄有一個created_at列(UTC)。Ruby on Rails:計算時間差

每個記錄持續24小時,我有我的模式在全球範圍內:現在

scope :available, -> { where(
    created_at: (Time.current - 24.hours)..Time.current 
) } 

,在前端側,這裏是我所需要的:

Record id 1: 23:59:12 
Record id 2: 22:23:03 
... 

經過一番研究,我發現了一些幫手做這項工作,但看起來很醜,這就是爲什麼我要求你的幫助。

這裏是我的(蘇茨基但工作)代碼:

# In my helper: 
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')}" 
end 

# And my the view: 
time_diff(Time.current - 24.hours, model_instance.created_at) 

我敢肯定,我錯過了一些真棒Rails的幫手這可能使這一切的一行:)

感謝您的閱讀我。

+1

近似會[distance_of_time_in_words](http://api.rubyonrails.org/classes/ActionView/Helpers/ DateHelper.html#方法-I-distance_of_time_in_words)。根據你的具體要求,在rails中沒有本地方式。 – rogelio

回答

0

那麼,你可以利用時間差寶石

http://www.rubydoc.info/github/tmlee/time_difference

start_time = Time.new(2013,1) 
end_time = Time.new(2014,1) 
TimeDifference.between(start_time, end_time).in_each_component 
=> {:years=>1.0, :months=>12.0, :weeks=>52.14, :days=>365.0, :hours=>8760.0, :minutes=>525600.0, :seconds=>31536000.0} 
+0

感謝您的回答,但我不確定爲這樣一個簡單的任務帶來寶石真的比輔助方法更好: -/ – Gann

0

你可以嘗試使用在Ruby核心庫的Time類。使用Time.at(seconds)創建自Epoch以來具有給定秒數的新Time對象。由於您的時間窗口小於24小時,因此您可以直接撥打strftime,而無需進行任何進一步計算。

def time_diff(start_time, end_time) 
seconds_diff = (start_time - end_time).abs 
Time.at(seconds_diff).utc.strftime "%H:%M:%S" 
end 

你應該避免調用到to_i因爲這將減少時間的準確性留下

+0

真棒,它的工作原理!謝謝! – Gann