简体   繁体   中英

Ruby on Rails: calculate time difference

I'm trying to calculate the "time left" for my records in Rails 5. My records have a created_at column (UTC).

Each record lasts 24 hours, I have a global scope on my model:

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

Now, on the front-end side, here is what I need:

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

After some researches, I've found some helper doing the work but it looks SO ugly, that's why I'm asking for your help.

Here is my (sucky but working) code:

# 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)

I'm sure I'm missing some awesome Rails helper which could make all this one-liner :)

Thanks for reading me.

Well, you can use the Time Difference Gem

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}

You could try using the Time class from Ruby Core Library. Using Time.at(seconds) to create a new Time object with the given number of seconds since the Epoch. Since your time window is less than 24 hours, you can call strftime directly without doing any further calculations.

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

You should avoid calling to to_i as it would reduce the accuracy of the time left

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM