Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 615
patrick Avatar asked Sep 25 '14 01:09

patrick


1 Answers

Just use duration + inspect

seconds = 86400 + 3600 + 15
ActiveSupport::Duration.build(seconds).inspect
=> "1 day, 1 hour, and 15.0 seconds"

Or a it can be a little be customized

ActiveSupport::Duration.build(seconds).parts.map do |key, value|
  [value.to_i, key].join 
end.join(' ')
=> "1days 1hours 15seconds"

P.S.

You can get seconds with

1.day.to_i
=> 86400

Time can be parsed only in ISO8601 format

ActiveSupport::Duration.parse("PT2H15M").inspect
=> "2 hours and 15 minutes"
like image 93
itsnikolay Avatar answered Sep 24 '22 17:09

itsnikolay