Ruby: Convert time to seconds?

后端 未结 8 659
甜味超标
甜味超标 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
    
    0 讨论(0)
  • 2020-12-28 08:55
    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.

    0 讨论(0)
提交回复
热议问题