If storing duration as integer seconds... question on building a helper

Ok, I’m new to rails (and Ruby)…

I’m trying to figure out the best practice for handling a duration
field (for example “time it takes someone to run a mile.” )

All I care about is seconds (not milliseconds) so figured I’d store
the field as an integer.

I want to allow the user to enter in the time manually as:

//1 minute 5 seconds:
1:05
OR
01:05

//2 hours 4 minutes 6 seconds:
2:04:06
OR
02:04:06

I have a helper that will convert seconds to a time display as:

def seconds_to_time seconds
Time.at(seconds).gmtime.strftime(’%R:%S’)
end

But how should I handle the conversion the other way around from the
input (ie convert 01:35 to seconds?)
Do I need to do some complex parsing of the String itself parsing out
: (remember it could be xx:xx:xx or just xx:xx )
or can I somehow leverage Time.parse ?

I would think this would come up quite often so there must be a best
practice or easy way to handle this kind of thing.

Thanks in advance

I currently decided to just use something like:

def time_to_seconds time_display
time = time_display.split(“:”)
seconds = 0
modifiers = [ 1, 60, 360 ]
time.each_with_index do | t, i |
seconds = seconds + ( t.to_i * modifiers[time.length -1 - i] )
end
return seconds
end

On Sun, Jul 5, 2009 at 7:23 PM, Rick[email protected] wrote:

//1 minute 5 seconds:
I have a helper that will convert seconds to a time display as:

I would think this would come up quite often so there must be a best
practice or easy way to handle this kind of thing.

Thanks in advance


Rick R

On Jul 5, 2009, at 8:44 PM, Rick wrote:

return seconds

end

If you’re just looking for a quick way to convert from hh:mm:ss to
seconds, how about:

time_string.split(’:’).inject(0){|a, m| a = a * 60 + m.to_i}

This presumes that the smallest increment in the string is seconds,
and the largest hours. However, that is how you described the problem.

WDYT?

On Mon, Jul 6, 2009 at 2:52 PM, s.ross[email protected] wrote:

time.each_with_index do | t, i |

Wow! That looks awesome. I’m new to ruby so just looked into the
inject method. I’ll test it shortly.

Thanks a lot. (It looks like it should work if you provided just
minutes and seconds 10:04 or hours:min:sec 1:14:05 )