How can I convert milliseconds in String format to HH: MM: SS format in Ruby in three lines of code?

@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

What is my current code, but I hate it. It looks dirty. It doesn't just look great. Maybe someone whose expert in ruby ​​could say how to do this, collects chains, reduces them, etc. And makes him good?

+5
source share
3 answers

The ruby ​​time class provides a function atfor retrieving time from seconds. Use it to cure.

miliseconds = 32290928
seconds = miliseconds/1000


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

OR to get utc time

#Get UTC Time
Time.at(seconds).utc.strftime("%H:%M:%S")
+8
source

You can wrap this in a helper method:

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"
+5
source

, @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

270921 + + + ? ()

+3

All Articles