Ruby: Convert time to seconds?

后端 未结 8 722
甜味超标
甜味超标 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:41

    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.

提交回复
热议问题