I have a number of seconds. Let's say 270921. How can I display that number saying it is xx days, yy hours, zz minutes, ww seconds?
+2
A:
Rails has an helper which converts distance of time in words. You can look its implementation: distance_of_time_in_words
Simone Carletti
2010-02-22 10:26:07
A:
Using Time.at will give you a Time-Instance:
Time.at(270921)
Hours:
Time.at(270921).hour
Time.at(270921).min
...
Please also take a look at the ruby doc for more information.
hkda150
2010-02-22 10:27:05
@hkda150: not sure if Time.at would work as it created time from `epoch`
Radek
2010-02-22 20:27:12
+4
A:
It can be done pretty concisely using divmod:
t = 270921
mm, ss = t.divmod(60) #=> [4515, 21]
hh, mm = mm.divmod(60) #=> [75, 15]
dd, hh = hh.divmod(24) #=> [3, 3]
puts "%d days, %d hours, %d minutes and %d seconds" % [dd, hh, mm, ss]
#=> 3 days, 3 hours, 15 minutes and 21 seconds
You could probably DRY it further by getting creative with collect, or maybe inject, but when the core logic is three lines it may be overkill.
Mike Woodhouse
2010-02-22 14:24:24