Ruby/Rails - How to convert seconds to time?

Vincent picture Vincent · Oct 19, 2010 · Viewed 20.8k times · Source

I need to perform the following conversion:

0     -> 12.00AM
1800  -> 12.30AM
3600  -> 01.00AM
...
82800 -> 11.00PM
84600 -> 11.30PM

I came up with this:

(0..84600).step(1800){|n| puts "#{n.to_s} #{Time.at(n).strftime("%I:%M%p")}"}

which gives me the wrong time, because Time.at(n) expects n to be number of seconds from epoch:

0     -> 07:00PM
1800  -> 07:30PM
3600  -> 08:00PM
...
82800 -> 06:00PM
84600 -> 06:30PM

What would be the most optimal, time zone independent solution for this transformation?

Answer

Mark Thomas picture Mark Thomas · Oct 19, 2010

The simplest one-liner simply ignores the date:

Time.at(82800).utc.strftime("%I:%M%p")

#-> "11:00PM"