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
Restoring Rails 3's Bundle Install Path... It's Now Install in My Root
Failed to Build Gem Native Extension When Install Redcloth-4.2.9 Install Linux
How to Redefine a Ruby Constant Without Warning
Ruby: Module, Require and Include
Rails: Testing Named Scopes with Rspec
Setting Up the Logger in Rails 3
Are There Any Ipython-Like Shells for Ruby or Rails
Copying Gems from Previous Version of Ruby in Rbenv
In Ruby, When Should You Use Self. in Your Classes
Check If Two Arrays Have the Same Contents (In Any Order)
Rspec 3 How to Test Flash Messages
Array.Join("\N") Not the Way to Join with a Newline
How to Convert a Comma-Separated String into an Array