Ruby: Convert Time to Seconds

Ruby: Convert time to seconds?

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

Ruby/Rails - How to convert seconds to time?

The simplest one-liner simply ignores the date:

Time.at(82800).utc.strftime("%I:%M%p")

#-> "11:00PM"

Converting hours, minutes and seconds to seconds in ruby

'12:34:56'.split(':').map(&:to_i).inject(0) { |a, b| a * 60 + b }
=> 45296

Converting Ruby timestamp to seconds in Epoch and back

Supposing your timestamp is a Ruby Time object:

puts time_stamp.strftime('%s')
puts time_stamp.to_i
timestamp = Time.at(628232400)

In case it is a DateTime object, you have the strftime and strptime methods at your disposal.

Convert Ruby Date to Integer

Date cannot directly become an integer. Ex:

$ Date.today
=> #<Date: 2017-12-29 ((2458117j,0s,0n),+0s,2299161j)>
$ Date.today.to_i
=> NoMethodError: undefined method 'to_i' for #<Date: 2017-12-29 ((2458117j,0s,0n),+0s,2299161j)>

Your options are either to turn the Date into a time then an Int which will give you the seconds since epoch:

$ Date.today.to_time.to_i
=> 1514523600

Or come up with some other number you want like days since epoch:

$ Date.today.to_time.to_i / (60 * 60 * 24)  ### Number of seconds in a day
=> 17529 ### Number of days since epoch

Converting seconds into hours only using Ruby in-built function - except the days

Now that I see what you're looking for, I offer this:

def seconds_to_hms(sec)
[sec / 3600, sec / 60 % 60, sec % 60].map{|t| t.to_s.rjust(2,'0')}.join(':')
end

Edit: Another option, even more concise:

def seconds_to_hms(sec)
"%02d:%02d:%02d" % [sec / 3600, sec / 60 % 60, sec % 60]
end

Sample output;

seconds_to_hms(164580)
=> "45:43:00"


Related Topics



Leave a reply



Submit