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
In plain ruby the fastest is the sum of time parts:
require 'benchmark'
require 'time'
Benchmark.bm do |x|
x.report('date') { 100_000.times { Time.now.to_i - Date.today.to_time.to_i } }
x.report('parse') { 100_000.times { Time.now.to_i - Time.parse('00:00').to_i } }
x.report('sum') { 100_000.times { Time.now.hour * 3600 + Time.now.min * 60 + Time.now.sec } }
end
user system total real
date 0.820000 0.000000 0.820000 ( 0.822578)
parse 1.510000 0.000000 1.510000 ( 1.516117)
sum 0.270000 0.000000 0.270000 ( 0.268540)
So, here is a method that takes timezone into account, if needed
def seconds_since_midnight(time: Time.now, utc: true)
time = time.utc if utc
time.hour * 3600 + time.min * 60 + time.sec
end