patrick patrick - 1 year ago 90
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 Source

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
    parts << "#{minutes} minute".pluralize(minutes) unless
    parts << "#{seconds} hour".pluralize(seconds)   unless
  end.join(', ')

# => '2 hours'

# => '2 hours, 1 minute'

# => '2 hours, 15 minutes'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download