Convert duration to hours:minutes:seconds (or similar) in Rails 3 or Ruby
See: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html
distance_of_time_in_words(3600)
=> "about 1 hour"
Rails - Get the time difference in hours, minutes and seconds
You can try with this:
def time_diff(start_time, end_time)
seconds_diff = (start_time - end_time).to_i.abs
hours = seconds_diff / 3600
seconds_diff -= hours * 3600
minutes = seconds_diff / 60
seconds_diff -= minutes * 60
seconds = seconds_diff
"#{hours.to_s.rjust(2, '0')}:#{minutes.to_s.rjust(2, '0')}:#{seconds.to_s.rjust(2, '0')}"
# or, as hagello suggested in the comments:
# '%02d:%02d:%02d' % [hours, minutes, seconds]
end
And use it:
time_diff(Time.now, Time.now-2.days-3.hours-4.minutes-5.seconds)
# => "51:04:04"
Rails - Convert hours and minutes to seconds then assign value to key
First, you can remove the hidden time_duration
field from the form, since it is not needed.
Then, you'll create a before_save
method for your car model:
car.rb
class Car < ActiveRecord::Base
belongs_to :service
belongs_to :tech
has_many :appointments
before_save :generate_time_duration
def generate_time_duration
self[:time_duration] = hours.hours.to_i + minutes.minutes.to_i
end
end
What this does: Before the car object is saved, it will run the generate_time_duration
method. What this method does is it simply sums the hours.to_i
and minutes.to_i
and assigns it to the car's time_duration
attribute.
Update old DB records
Since you're adding this functionality in your application AFTER records have already been created, here is a quick way to update all of your current records:
- In your command line, open a rails console by running the command
rails c
(orrails console
) - In the console, run this command:
Car.all.each { |c| c.save! }
This is a quick, one-time fix that will loop through all Car records, save them, and subsequently update their time_duration
fields.
Dividing seconds into hours, minutes and seconds
You could do it like this:
seconds = 219
hours = seconds / 3600
seconds -= hours * 3600
minutes = seconds / 60
seconds -= minutes * 60
puts "#{hours} hours, #{minutes} minutes and #{seconds} seconds"
Convert duration in seconds to hours and minutes and skip empty values
Why not just something simple like this:
def to_hms(time)
hours = time / 3600
minutes = (time / 60) % 60
if (hours > 0 and minutes > 0)
'%d h %d m' % [ hours, minutes ]
elsif (hours > 0)
'%d h' % hours
elsif (minutes > 0)
'%d m' % minutes
end
end
Where this produces the desired results:
to_hms(63000)
# => "17 h 30 m"
to_hms(28800)
# => "8 h"
to_hms(1800)
# => "30 m"
Converting hours, minutes and seconds to seconds in ruby
'12:34:56'.split(':').map(&:to_i).inject(0) { |a, b| a * 60 + b }
=> 45296
how to convert 270921sec into days + hours + minutes + sec ? (ruby)
It can be done pretty concisely using divmod
:
t = 270921
mm, ss = t.divmod(60) #=> [4515, 21]
hh, mm = mm.divmod(60) #=> [75, 15]
dd, hh = hh.divmod(24) #=> [3, 3]
puts "%d days, %d hours, %d minutes and %d seconds" % [dd, hh, mm, ss]
#=> 3 days, 3 hours, 15 minutes and 21 seconds
You could probably DRY it further by getting creative with collect
, or maybe inject
, but when the core logic is three lines it may be overkill.
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
Rails 3 + Daemons Gem: Exception When Querying Model
Ruby Instance Method & Conditional Local Variable Assignment with Same Name
Rails + Google Calendar API Events Not Created
Proc Throws Error When Used with Do End
Why Use Gems for Serving Assets Instead of the Vendor File
Rails Migration Complains About Undefined Method 'Attachment' Using Paperclip
Invalid Source Reflection MACro :Has_Many :Through
Hook Before All Delyed Job Success Callback to Save Successfully Completed Jobs
How to Return a Group of Sequential Numbers That Might Exist in an Array
Managing Conflicting Versions of Ruby Gems
How to Escape All Characters with Special Meaning in Regex
On Destroying Session via Devise "Couldn't Find User with 'Id'=Sign_Out"
Rspec: How to Write Unit Test Case to Receive an Exception Which Is Getting Raised in Private Method
How to Install Ruby Gems on MAC
How to Seed the Production Database Using the Capistrano Gem