Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/Rails - How to convert seconds to time?

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?

like image 348
Vincent Avatar asked Oct 18 '10 22:10

Vincent


2 Answers

The simplest one-liner simply ignores the date:

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

#-> "11:00PM"
like image 95
Mark Thomas Avatar answered Oct 01 '22 07:10

Mark Thomas


Not sure if this is better than

(Time.local(1,1,1) + 82800).strftime("%I:%M%p")


def hour_minutes(seconds)
  Time.at(seconds).utc.strftime("%I:%M%p")
end


irb(main):022:0> [0, 1800, 3600, 82800, 84600].each { |s| puts "#{s} -> #{hour_minutes(s)}"}
0 -> 12:00AM
1800 -> 12:30AM
3600 -> 01:00AM
82800 -> 11:00PM
84600 -> 11:30PM

Stephan

like image 38
Stephan Wehner Avatar answered Oct 01 '22 07:10

Stephan Wehner