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

时间:2010-10-18 22:30:24

标签: ruby-on-rails ruby time timestamp seconds

我需要执行以下转换:

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

这种转型的最佳时区独立解决方案是什么?

4 个答案:

答案 0 :(得分:33)

最简单的单行简单地忽略了日期:

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

#-> "11:00PM"

答案 1 :(得分:3)

不确定这是否优于

(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

斯蒂芬

答案 2 :(得分:2)

两项优惠:

精心制作的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

答案 3 :(得分:1)

在其他解决方案中,当跨越24小时制时限时,小时计数器将重置为00。还要注意,Time.at会四舍五入,因此,如果输入中有小数秒,它将给出错误的结果(例如,当t=479.9时,Time.at(t).utc.strftime("%H:%M:%S")将给出00:07:59不是00:08:00`,这是正确的。)

如果您想将任意秒数(甚至大于24小时间隔的高计数)转换为不断增加的HH:MM:SS计数器,并处理可能的小数秒,请尝试以下操作:

# Will take as input a time in seconds (which is typically a result after subtracting two Time objects),
# and return the result in HH:MM:SS, even if it exceeds a 24 hour period.
def formatted_duration(total_seconds)
  total_seconds = total_seconds.round # to avoid fractional seconds potentially compounding and messing up seconds, minutes and hours
  hours = total_seconds / (60*60)
  minutes = (total_seconds / 60) % 60 # the modulo operator (%) gives the remainder when leftside is divided by rightside. Ex: 121 % 60 = 1
  seconds = total_seconds % 60
  [hours, minutes, seconds].map do |t|
    # Right justify and pad with 0 until length is 2. 
    # So if the duration of any of the time components is 0, then it will display as 00
    t.round.to_s.rjust(2,'0')
  end.join(':')
end

根据@springerigor的建议和https://gist.github.com/shunchu/3175001讨论中的建议进行了修改