Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Convert time to seconds?

Tags:

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).

like image 788
Shpigford Avatar asked Sep 29 '10 17:09

Shpigford


2 Answers

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 
like image 156
Daniel Vandersluis Avatar answered Sep 29 '22 11:09

Daniel Vandersluis


Yet another implementation:

Time.now.to_i - Date.today.to_time.to_i # seconds since midnight 
like image 42
Teddy Avatar answered Sep 29 '22 10:09

Teddy