Ruby: Convert time to seconds?

后端 未结 8 706
甜味超标
甜味超标 2020-12-28 08:16

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

8条回答
  •  一整个雨季
    2020-12-28 08:49

    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
    

提交回复
热议问题