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

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

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 Sun, Jul 5, 2009 at 7:23 PM, Rick<[email protected]> wrote:
>> 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
>>
>
>
>
> -- 
> Rick R
>
> >


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to