Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In Rails, I am trying to convert seconds into hours only. But coincidently function gives something else.

For example - Second = 164580
Output like : 45:43:0

After some interval like 24 hours, it converts into day as well. I am trying to use any Ruby inbuilt function to get total hours only.

like image 603
Rubyist Avatar asked Mar 06 '15 21:03

Rubyist


People also ask

Is there some sort of built in Ruby function to handle 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 a DateTime object, and then multiply the hour by 3600 and the minute by 60 to get the number of seconds:

What is the use of time in Ruby?

The Ruby Time Class. You can use the Time class in Ruby to represent a time & date. This date has three components: And time: This information is stored by the Time class as the number of seconds since the Epoch, also known as Unix time.

Is it possible to do time Math in pure Ruby?

These methods are not available in pure Ruby, they are added by the ActiveSupport component of Rails. Here you can find some examples, notice how these methods don’t return Time or Date objects, but a custom ActiveSupport class. You can do time math with these & get things like tomorrow’s date:

How to get the number of seconds in a string?

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


1 Answers

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"
like image 180
Mark Thomas Avatar answered Sep 19 '22 04:09

Mark Thomas