DEV Community

Discussion on: Daily Challenge #21 - Human Readable Time

Collapse
 
rocketrobc profile image
Rob Cornish • Edited

Ruby

SECONDS = 1
MINUTES = 60
HOURS = 3600
DAYS = 86400
YEARS = 31536000

NAMES = %w[year day hour minute second]

def calculate_durations(seconds)
  [YEARS, DAYS, HOURS, MINUTES, SECONDS].map do |period|
    next if period > seconds
    quantity = seconds / period
    seconds -= (quantity * period)
    quantity
  end
end

def trim_durations(durations)
  while durations[-1].nil?
    durations.pop
  end
  durations
end

def format_duration(seconds)
  durations = trim_durations(calculate_durations(seconds))
  output = ''
  NAMES.each.with_index do |name, i|
    next if durations[i].nil?
    name += 's' if durations[i] > 1
    unless i == durations.size - 1
      output += (durations[i].to_s + ' ' + name)
      output += ', ' if i < durations.size - 2
    else
      output += (' and ' + durations[i].to_s + ' ' + name)
    end
  end
  output
end

puts "4500 seconds: #{format_duration(4500)}"
puts "2000487 seconds: #{format_duration(2000487)}"
puts "42000487 seconds: #{format_duration(42000487)}"
puts "1563739200 seconds: #{format_duration(1563739200)}"

4500 seconds: 1 hour and 15 minutes
2000487 seconds: 23 days, 3 hours, 41 minutes and 27 seconds
42000487 seconds: 1 year, 121 days, 2 hours, 48 minutes and 7 seconds
1563739200 seconds: 49 years, 213 days and 20 hours