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 fro
You can use DateTime#parse to turn a string into a DateTime
object, and then multiply 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
require 'time'
def seconds_since_midnight(time)
Time.parse(time).hour * 3600 + Time.parse(time).min * 60 + Time.parse(time).sec
end
puts seconds_since_midnight("18:46")
All great answers, this is what I ended up using.