patrick patrick - 6 months ago 16
Ruby Question

Display duration in a human readable format such as "X hours, Y minutes"

I am using Rails 4, Ruby 2.1 with PostgreSQL.

I have a database field called "duration" which is an interval data type.

When pulling out the data in this column it returns in the format of hh:mm:ss e.g. 01:30:00.

I am trying to figure out a way to display this as:
1 hour, 30 minutes

Other examples:
02:00:00 to 2 hours
02:15:00 to 2 hours, 15 minutes
02:01:00 to 2 hours, 1 minute

Any advice appreciated.

Answer

I would start with something like this:

def duration_of_interval_in_words(interval)
  hours, minutes, seconds = interval.split(':').map(&:to_i)

  [].tap do |parts|
    parts << "#{hours} hour".pluralize(hours)       unless hours.zero?
    parts << "#{minutes} minute".pluralize(minutes) unless minutes.zero?
    parts << "#{seconds} hour".pluralize(seconds)   unless seconds.zero?
  end.join(', ')
end

duration_of_interval_in_words('02:00:00')
# => '2 hours'

duration_of_interval_in_words('02:01:00')
# => '2 hours, 1 minute'

duration_of_interval_in_words('02:15:00')
# => '2 hours, 15 minutes'