How to convert seconds into weeks, days, hours, minutes, and seconds in Ruby

1 Answer

0 votes
=begin
Use integer division and modulo:

1 minute = 60 seconds
1 hour   = 60 minutes
1 day    = 24 hours
1 week   = 7 days
=end

# Constants belong at the top level in Ruby
SECS_PER_MIN  = 60
SECS_PER_HOUR = 60 * SECS_PER_MIN
SECS_PER_DAY  = 24 * SECS_PER_HOUR
SECS_PER_WEEK = 7  * SECS_PER_DAY

=begin
    Convert a total number of seconds into weeks, days, hours,
    minutes, and seconds. The function receives the total seconds
    and returns each component in a hash.
=end
def convert_seconds(total_seconds)
  # Compute each unit using integer division and modulo
  weeks = total_seconds / SECS_PER_WEEK
  total_seconds %= SECS_PER_WEEK

  days = total_seconds / SECS_PER_DAY
  total_seconds %= SECS_PER_DAY

  hours = total_seconds / SECS_PER_HOUR
  total_seconds %= SECS_PER_HOUR

  minutes = total_seconds / SECS_PER_MIN
  seconds = total_seconds % SECS_PER_MIN

  {
    weeks: weeks,
    days: days,
    hours: hours,
    minutes: minutes,
    seconds: seconds
  }
end

seconds = 1_000_000

result = convert_seconds(seconds)

puts "#{result[:weeks]} weeks, " \
     "#{result[:days]} days, " \
     "#{result[:hours]} hours, " \
     "#{result[:minutes]} minutes, " \
     "#{result[:seconds]} seconds"



=begin
run:

1 weeks, 4 days, 13 hours, 46 minutes, 40 seconds

=end

 



answered May 20 by avibootz

Related questions

...