views:

60

answers:

3

How can I convert a time like 10:30 to seconds? Is there some sort of built in Ruby function to handle that?

Basically trying to figure out the number of seconds from midnight (00:00) to a specific time in the day (such as 10:30, or 18:45).

+3  A: 

You can use DateTime#parse to turn a string into a DateTime object, and then multiple the hour by 3600 and the minute by 60 to get the number of seconds:

require 'date'

# DateTime.parse throws ArgumentError if it can't parse the string
if dt = DateTime.parse("10:30") rescue false 
  seconds = dt.hour * 3600 + dt.min * 60 #=> 37800
end

As jleedev pointed out in the comments, you could also use Time#seconds_since_midnight if you have ActiveSupport:

require 'active_support'
Time.parse("10:30").seconds_since_midnight #=> 37800.0
Daniel Vandersluis
This seems to require Active Support.
jleedev
Also, there’s a `seconds_since_midnight` method.
jleedev
In regards to the ArgumentError...is there a way to convert a number to time? So say the input was just "8"...I'd want to convert to "8:00"
Shpigford
@jleedev Updated to use `DateTime#parse` instead.
Daniel Vandersluis
A: 

Perhaps there is a more succinct way, but:

t = Time.parse("18:35")
s = t.hour * 60 * 60 + t.min * 60 + t.sec

would do the trick.

bnaul
+2  A: 

The built in time library extends the Time class to parse strings, so you could use that. They're ultimately represented as seconds since the UNIX epoch, so converting to integers and subtracting should get you what you want.

require 'time'
m = Time.parse('00:00')
t = Time.parse('10:30')

(t.to_i - m.to_i)
=> 37800

There's also some sugar in ActiveSupport to handle these types of things.

Derek