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).
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).
You can use
DateTime#parse
to turn a string into aDateTime
object, and then multiply the hour by 3600 and the minute by 60 to get the number of seconds:As jleedev pointed out in the comments, you could also use
Time#seconds_since_midnight
if you have ActiveSupport: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.
There's also some sugar in ActiveSupport to handle these types of things.
I like these answers very much, especially Teddy's for its tidyness.
There's one thing to note. Teddy's answer gives second of day in current region and I haven't been able to convert
Date.today.to_time
to UTC. I ended up with this workaround:It's based on the fact that
Time.now.to_i
gives seconds since Unix Epoch which is always1970-01-01T00:00:00Z
, regardless of your current time zone. And the fact that there's 86400 seconds in a day as well. So this solution will always give you seconds since last UTC midnight.Yet another implementation:
Perhaps there is a more succinct way, but:
would do the trick.
You can simply use