Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I convert milliseconds in String format to HH:MM:SS format in Ruby in under 3 lines of code?

Tags:

ruby

@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

That's my current code but I hate it. It's looks messy. It doesn't just look great at all. Maybe someone whose an expert in ruby could tell how to do this by chaining collects, reduces etc and making it look good?

like image 411
qwexar Avatar asked Feb 04 '13 12:02

qwexar


3 Answers

Time class ruby provides provides at function to get time from seconds. Use this it will 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")
like image 169
Taimoor Changaiz Avatar answered Nov 16 '22 18:11

Taimoor Changaiz


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"
like image 38
ichigolas Avatar answered Nov 16 '22 20:11

ichigolas


Nice solution given by @Mike Woodhouse :

Use 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

Answer is how to convert 270921sec into days + hours + minutes + sec ? (ruby)

like image 39
Rahul Tapali Avatar answered Nov 16 '22 20:11

Rahul Tapali