5
@scores_raw.each do |score_raw|
  # below is code if time was being sent in milliseconds
  hh = ((score_raw.score.to_i)/100)/3600
  mm = (hh-hh.to_i)*60
  ss = (mm-mm.to_i)*60
  crumbs = [hh,mm,ss]
  sum = crumbs.first.to_i*3600+crumbs[1].to_i*60+crumbs.last.to_i
  @scores << {:secs => sum, :hms => hh.round.to_s+":"+mm.round.to_s+":"+ss.round.to_s}
  @scores_hash << {:secs => sum, :hms => hh.round.to_s+":"+mm.round.to_s+":"+ss.round.to_s}
  # milliseconds case end
end

这是我当前的代码,但我讨厌它。看起来很乱 它不仅看起来很棒。也许某个红宝石专家可以通过链接收集、减少等并使其看起来不错来告诉如何做到这一点?

4

3 回答 3

8

时间类 ruby​​ 提供了at从秒中获取时间的功能。使用它会治愈。

miliseconds = 32290928
seconds = miliseconds/1000


Time.at(seconds).strftime("%H:%M:%S")

或获取UTC时间

#Get UTC Time
Time.at(seconds).utc.strftime("%H:%M:%S")
于 2013-02-04T15:34:07.237 回答
5

您可以将其包装在辅助方法中:

def format_milisecs(m)
  secs, milisecs = m.divmod(1000) # divmod returns [quotient, modulus]
  mins, secs = secs.divmod(60)
  hours, mins = mins.divmod(60)

  [secs,mins,hours].map { |e| e.to_s.rjust(2,'0') }.join ':'
end

format_milisecs 10_600_00
=> "03:13:20"
于 2013-02-04T12:54:19.583 回答
3

@Mike Woodhouse 给出的不错的解决方案:

使用divmod

t = 270921000
ss, ms = t.divmod(1000)          #=> [270921, 0]
mm, ss = ss.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

答案是 如何将 270921sec 转换为天 + 小时 + 分钟 + 秒?(红宝石)

于 2013-02-04T12:54:59.040 回答