I'm trying to find the best way to generate the following output
<name> job took 30 seconds
<name> job took 1 minute and 20 seconds
<name> job took 30 minutes and 1 second
<name> job took 3 hours and 2 minutes
I started this code
def time_range_details
time = (self.created_at..self.updated_at).count
sync_time = case time
when 0..60 then "#{time} secs"
else "#{time/60} minunte(s) and #{time-min*60} seconds"
end
end
Is there a more efficient way of doing this. It seems like a lot of redundant code for something super simple.
Another use for this is:
<title> was posted 20 seconds ago
<title> was posted 2 hours ago
The code for this is similar, but instead i use Time.now:
def time_since_posted
time = (self.created_at..Time.now).count
...
...
end
If you need something more "precise" than
distance_of_time_in_words
, you can write something along these lines:Oh, one remark on your code:
is really bad way to get the difference. Use simply:
There are two methods in
DateHelper
that might give you what you want:time_ago_in_words
distance_of_time_in_words
chronic_duration parses numeric time to readable and vice versa
If you want to show significant durations in the seconds to days range, an alternative would be (as it doesn't have to perform the best):
Alternatively you may be only interested in stripping the seconds part when it doesn't matter (also demonstrating another approach):
Hope that helps.
Rails has a
DateHelper
for views. If that is not exactly what you want, you may have to write your own.@Mladen Jablanović has an answer with good sample code. However, if you don't mind continuing to customize a sample humanize method, this might be a good starting point.
This gives you an array of values and unit names that you can manipulate.
If the first element is non-zero, it is the number of days. You may want to write code to handle multiple days, like showing weeks, months, and years. Otherwise, trim off the leading
0
values, and take the next two.The code even finds use for a ruby
while
statement.There is problem with
distance_of_time_in_words
if u ll pass there 1 hour 30 min it ll return about 2 hoursSimply add in helper:
Basically just pass your data in seconds.