Search code examples
rubytime

Ruby: Convert time to seconds?


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


Solution

  • 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 Josh Lee 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