Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Displaying the difference between times in Ruby (See related posts)

This function converts the number of seconds into hours, minutes, and seconds.

require 'time'

def seconds_fraction_to_time(seconds)
  hours = mins = 0
  if seconds >=  60 then
    mins = (seconds / 60).to_i 
    seconds = (seconds % 60 ).to_i

    if mins >= 60 then
      hours = (mins / 60).to_i 
      mins = (mins % 60).to_i
    end
  end
  [hours,mins,seconds]
end

departed_house = Time.parse("07:34")
arrived_at_supermarket = Time.parse("09:10")
travel_duration_in_seconds =  arrived_at_supermarket - departed_house

hours, minutes, seconds = seconds_fraction_to_time(travel_duration_in_seconds)

puts "The journey from my home to the supermarket took #{hours} hour(s), #{minutes} minutes, and #{seconds} seconds."

Output:
The journey from my home to the supermarket took 1 hour(s), 36 minutes, and 0 seconds.

References:
- Class: Time [ruby-doc.org]
- Working with Dates and Times in Ruby [techotopia.com]
- Numbers in Ruby [rubylearning.com]

You need to create an account or log in to post comments to this site.


Click here to browse all 7286 code snippets

Related Posts