I’m sure you’ve probably seen this question in your programming classes.. I decided I wanted to play with Ruby again and was remind of this problem, so thought it might be fun as a simple exercise to do this in Ruby.
The problem is to take a long integer and convert it to hours, minutes and seconds. This is a common issue in games, for example, where a countdown timer is represent internally in seconds. But players don’t want to see some huge number like 43678 seconds. They’d rather see 12:07:58 for hours, minutes and seconds. A couple of uses of the mod operator, and a couple of uses of the built-in formatter and you’re good to go.
Update: I wanted to clean up the code a bit more and put the ruby equivalent of a “main” via the __FILE__
check. This way you can just reuse the code via require if you so desire.
#!/usr/bin/env ruby class TimeFormatter def format_time (timeElapsed) @timeElapsed = timeElapsed #find the seconds seconds = @timeElapsed % 60 #find the minutes minutes = (@timeElapsed / 60) % 60 #find the hours hours = (@timeElapsed/3600) #format the time return hours.to_s + ":" + format("%02d",minutes.to_s) + ":" + format("%02d",seconds.to_s) end end if __FILE__ == $0 formatter = TimeFormatter.new puts formatter.format_time(43678) end
How do you go the other way? In other words, convert from a string in hours, minutes, and seconds to a quantity of seconds (or milliseconds)?
Something like this should work:
require 'time'
if t = Time.parse("30/Nov/2009 16:29:30 +0100") rescue false
seconds = t.hour * 3600 + t.min * 60 + t.sec
end