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.
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:
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.
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:
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With