Ruby / Rails – 如何将秒转换为时间?

我需要执行以下转换:

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

我想出了这个:

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

这给了我错误的时间,因为Time.at(n)期望n是epoch的秒数:

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

什么是最佳的,时区无关的解决方案?

最简单的单线程只是忽略了日期:

 Time.at(82800).utc.strftime("%I:%M%p") #-> "11:00PM" 

不确定这是否优于

 (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 

斯蒂芬

两个优惠:

精心设计的DIY解决方案:

 def toClock(secs) h = secs / 3600; # hours m = secs % 3600 / 60; # minutes if h < 12 # before noon ampm = "AM" if h = 0 h = 12 end else # (after) noon ampm = "PM" if h > 12 h -= 12 end end ampm = h <= 12 ? "AM" : "PM"; return "#{h}:#{m}#{ampm}" end 

时间解决方案:

 def toClock(secs) t = Time.gm(2000,1,1) + secs # date doesn't matter but has to be valid return "#{t.strftime("%I:%M%p")} # copy of your desired format end 

HTH